Tagged: jQuery RSS

  • Mohammad Jangda 9:23 pm on September 13, 2010 Permalink | Reply
    Tags: ajax, callbacks, , jQuery   

    WordPress Tip: Hooking into Widget Save Callback 

    John Gadbois turned some code I gave him into short and useful write-up on how to hook into AJAX calls triggered when saving widgets. It makes use of jQuery’s Global AJAX event handlers, which allow for some very cool things, especially when you’re working with external libraries that use the jQuery AJAX methods. A future blog post will cover how plugins can use the ajaxSend event to hook into WordPress’ autosave.

     
  • Mohammad Jangda 5:23 pm on July 22, 2010 Permalink | Reply
    Tags: , , jQuery   

    jQuery Plugin: HTML5 Inline Data 

    HTML5 Data Attributes are sexy.

    What’s sexier is an easy way to work with these data attributes using jQuery.

    Sure, you could do something like:

    jQuery('#pancakes').attr('data-type');
    

    But who wants to type the “data-” prefix over and over again?

    So, here’s a quick little plugin I whipped up. It’s probably terrible when it comes to jQuery plugin standards (I do WordPress plugins, not jQuery), but it works. It works as a getter and setter.

    Bonus: If you’re using jQuery 1.4.1+, the plugin supports well-formed JSON objects as data attribute values.


    /*
    * Inline Data - get and set HTML5 data attributes! Yay!
    *
    * Copyright (c) 2010 Mohammad Jangda (http://digitalize.ca), Vortex Mobile (http://www.vortexmobile.ca)
    *
    * Licensed under the MIT license:
    * http://www.opensource.org/licenses/mit-license.php
    *
    */
    
    (function($) {
        $.fn.inlinedata = function(name, value) {
    
            var prefix = 'data-';
            var attr = prefix + name;
            var values = []
    
            this.each(function(i) {
                var attrValue;
    
                // Setting values
                if(value) {
                    // If an array is passed, the array index should correspond to the collection index
                    if($.isArray(value)) {
                        // Check, check, check the index. Because out of bounds exceptions are the devil!
                        if(typeof(value[i]) !== 'undefined')
                            attrValue = value[i];
                        else
                            attrValue = '';
                    } else {
                        // Not an array, so we're just giving all the elements the same value
                        attrValue = value;
                    }
                    this.setAttribute(attr, attrValue);
                } else {
                    // Getting values
                    attrValue = this.getAttribute(attr);
    
                    try {
                        // try parsing as JSON
                        attrValue = jQuery.parseJSON(attrValue);
                    } catch(e) { }
                }
                attrValue = (attrValue) ? attrValue : '';
                values.push(attrValue);
            });
    
            if(values.length == 1)
                return values[0]
    
            return values;
        }
    })(jQuery);
    

    Usage is simple:


    
    
    
    
    
    
    
    
    
    
    
    
    

     
  • Mohammad Jangda 3:36 pm on April 29, 2010 Permalink | Reply
    Tags: , , , , jQuery,   

    JavaScript Tip: Save me from console.log errors 

    It’s bound to happen. You build yourself a sweet webapp with some sweet javascript action and you unleash it to the world only to get angry emails yelling, “IT DOESn’T WoRK! FIX iT okAy?” And it’s the darndest problem because it’s happening to both IE and Firefox users (Chrome and Safari users have been silent) and you can’t replicate it.

    And then you spend hours trying to figure out the problem to no avail, leaving you scratching that magnificent head of yours with luscious, flowing hair. You just can’t replicate the problem. But then, after hours and days of staring intently at the screen, you find it. It’s a rogue console.log call that you forgot to comment out. And then you spend the remainder of the week chastising yourself for being stupid.

    It happens. (To be fair, it’s not your fault that your users don’t have Firebug or IE Developer Tools installed. Blame it on Mozilla/Microsoft.)

    But there’s an easy solution. Just copy the following javascript somewhere in your project, and rest easy:


    if(typeof(console) === 'undefined') {
        var console = {}
        console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
    }
    

     
    • Chris Marisic 3:38 pm on March 8, 2011 Permalink | Reply

      Nice article, I just came across this bug affecting orbit jquery slider and posted your article to them https://github.com/zurb/orbit/issues/6 :)

    • Jatinder Assi 3:52 pm on September 27, 2011 Permalink | Reply

      Actually the if stmt will always gets executed in IE 8, even when the developer tools window is open, thus resulting in the console object to be always a nul object.

      Instead here is the solution that I used after modifying your code:

      try
      {
      console.log('test');
      }
      catch(err){
      var console = {};
      console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
      }

  • Mohammad Jangda 12:42 pm on February 23, 2010 Permalink | Reply
    Tags: , jqtouch, jQuery   

    jQTouch: Tap vs Click 

    jQTouch has a sweet feature which adds a fast touch or “tap” event. It’s pointless for me to try and rephrase, so learn all about it on the jQTouch blog: Milliseconds Responsiveness and the Fast Tap

    Now, the only downside to the tap event, is that it doesn’t work on anything other than Mobile Safari. So for iPhones, you can use tap event, but non-iPhones, you have to use click event. You could just make things easy on yourself and use clicks across the board, but I can tell you that the tap event immensely increases the performance and responsivity for jQTouch apps on iPhones. Good news is, there’s an easy way to work with both.

    The code below was inspired by Samuel’s message on the jQTouch Google Group.

    <script type="text/javascript">
    var userAgent = navigator.userAgent.toLowerCase();
    var isiPhone = (userAgent.indexOf('iphone') != -1 || userAgent.indexOf('ipod') != -1) ? true : false;
    clickEvent = isiPhone ? 'tap' : 'click';
    </script>
    

    You can now easily bind your events as follows:

    <a href="#link" id="mylink">Click or Tap me!</a>
    <script type="text/javascript">
    $('#mylink').bind(clickEvent, function() {
        e.preventDefault();
        alert('Yay! You just ' + clickEvent + 'ed me!');
    });
    </script>
    

    Note: in my testing, the tap event doesn’t register too well on the iPod Touch. If that seems to be the case, I’d recommend defaulting iPod Touches to use clicks instead. However, since the iPod Touch user agent includes the term “iPhone”, we have to un-include it from our tap list:

    <script type="text/javascript">
    var userAgent = navigator.userAgent.toLowerCase();
    var isiPhone = (userAgent.indexOf('iphone') != -1) ? true : false;
    if(userAgent.indexOf('ipod') != -1) isiPhone = false; // turn off taps for iPod Touches
    clickEvent = isiPhone ? 'tap' : 'click';
    </script>
    
     
    • rblon 7:05 am on May 11, 2010 Permalink | Reply

      It appears that if you have <a href=”…” rel=”nofollow”> that, with an iPhone, tapping does activate the link, but not the click event. So

      “You could just make things easy on yourself and use clicks across the board”

      actually doesn’t hold (assuming you want the event handler to run). So to me it seems you always have to include this bit of code.

    • rblon 7:08 am on May 11, 2010 Permalink | Reply

      sorry for the formatting of my previous comment (I had included example html code).

      It should say:

      It appears that if you have “an anchor tag with href”, that, with an Iphone….

    • John 2:58 pm on July 7, 2010 Permalink | Reply

      I run code on a real iPhone / iPod Touch / iPad, but also find that it’s useful to run the same code in Safari (in emulation mode), and in the iPhone simulator (which seems not to handle tap!!??).

      So I’m doing something like this:

      var isRealMobile = (userAgent.indexOf(‘iphone’) != -1 ||
      userAgent.indexOf(‘ipod’) != -1 ||
      userAgent.indexOf(‘ipad’) != -1) &&
      userAgent.indexOf(‘safari’) == -1 && userAgent.indexOf(‘simulator’) == -1;
      var touchEvent = isRealMobile ? ‘tap’ : ‘click’;

      $(“#something”).bind(touchEvent, something);

      Here are the user agent strings I looked at:

      Safari emulating:
      Mozilla/5.0 (iPod; U; CPU iPhone OS 3_1_3 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7E18 Safari/528.16

      Simulator:
      Mozilla/5.0 (iPhone Simulator; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/8A293

      Real iPhone:
      Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/8A293

    • Tumble Weed 11:30 am on August 5, 2010 Permalink | Reply

      Sooooooooooo much appreciated!!!!!

    • Michael 3:28 am on September 10, 2010 Permalink | Reply

      All, the very good advice of John, but I wonder is it a good idea to track ipod ipad and iphone via indexOf. What if Apple added another mobile, iSomething? Would it not be better to track AppleWebKit.*Mobile using a regexp?

    • Michael 3:32 am on September 10, 2010 Permalink | Reply

      Another thing I found is that on the desktop safari with emulated iphone i had to use “click” and not “tap”. Since I debug on my local host, it is enough to exclude localhost

    • David Mark 1:58 am on November 21, 2010 Permalink | Reply

      The cross-browser solution is to attach both click and tap listeners and cancel one of them the first time through. You know you will get a tap first, so remove the click listener on tap. If the click listener fires, remove the tap listener.

      All of this UA sniffing is for the birds (as you have found out).

    • Chris 9:24 am on June 17, 2011 Permalink | Reply

      I use something similar, checking for iPhone, iPod and iPad, as well as simulator and general mobile devices

      var userAgent = navigator.userAgent.toLowerCase();
      var isMobile = (userAgent.indexOf('iphone') != -1 || userAgent.indexOf('ipod') != -1 || userAgent.indexOf('mobile') || userAgent.indexOf('ipad')) ? true : false;
      clickEvent = isMobile ? 'tap' : 'click';

    • Oskar 8:53 am on November 4, 2011 Permalink | Reply

      You have an error in your code:
      $(‘#mylink’).bind(clickEvent, function() {
      e.preventDefault();
      alert(‘Yay! You just ‘ + clickEvent + ‘ed me!’);
      });

      It should be:
      function(e)

  • Mohammad Jangda 9:33 am on February 10, 2010 Permalink | Reply
    Tags: awesome, , jQuery   

    jQuery.data() = love 

    Why did I never know about jQuery.data()?

    More details to come about fun things you can do with it.

     
  • Mohammad Jangda 1:01 pm on November 25, 2009 Permalink | Reply
    Tags: , jQuery   

    jQuery tip: Visually separating DOM elements in code 

    Here’s a quick tip I picked up from Chris Coyier (the genius behind CSS-Tricks and Digging Into WordPress).

    To help keep variables that contain DOM elements visually distinct from other regular variables, just prepend a $ (dollar sign) to them. Example:

    <script type="text/javascript">
    // assign the variable
    var $div = jQuery('#myDiv');
    // Do stuff to it
    $div.animate({width: '200%'}, 1500);
    </script>
    

    This way, you can easily pick out which variables contain DOM elements when viewing code, without resorting to excessive naming conventions (such as divContainer or divDomObject, etc.). Your code stays clean, lean, and easy to read.

    Rock on.

     
c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
l
go to login
h
show/hide help
shift + esc
cancel