Category Archives: Javascript

JQuery – Accessing Native Properties and Methods

So you’ve learned a bit of JavaScript, and have learned that, for instance, on anchor tags, you can access attribute values directly:

var anchor = document.getElementById('someAnchor');
//anchor.id
// anchor.href
// anchor.title
// .etc

The only problem is that this doesn’t seem to work when you reference the DOM elements with jQuery, right? Well of course not.


// Fails
var id = $('#someAnchor').id;

So, should you need to access the href attribute (or any other native property or method for that matter), you have a handful of options.

// OPTION 1 - Use jQuery
var id = $('#someAnchor').attr('id');

// OPTION 2 - Access the DOM element
var id = $('#someAnchor')[0].id;

// OPTION 3 - Use jQuery's get method
var id = $('#someAnchor').get(0).id;

// OPTION 3b - Don't pass an index to get
anchorsArray = $('.someAnchors').get();
var thirdId = anchorsArray[2].id;

JQuery – Detect AJAX Requests with PHP

Certainly, for the huge majority of our projects, we can’t only rely on JavaScript for things like validation, or AJAX requests. What happens when JavaScript is turned off? For this very reason, a common technique is to detect whether an AJAX request has been made with your server-side language of choice.

jQuery makes this ridiculously simple, by setting a header from within the $.ajax method.

 // Set header so the called script knows that it's an XMLHttpRequest
 // Only send the header if it's not a remote XHR
 if ( !remote ) {
 xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
 }
 

With this header set, we can now use PHP (or any other language) to check for this header, and proceed accordingly. For this, we check the value of $_SERVER['HTTP_X_REQUESTED_WITH'].

JQuery – Passing an Attribute Object

As of jQuery 1.4, we can now pass an object as the second parameter of the jQuery function. This is helpful when we need to insert new elements into the DOM. For example:

Before

    $('')
      .attr({
        id : 'someId',
        className : 'someClass',
        href : 'somePath.html'
      });

After

    $('', {
        id : 'someId',
        className : 'someClass',
        href : 'somePath.html'
    });

Not only does this save a few characters, but it also makes for cleaner code. In addition to element attributes, we can even pass jQuery specific attributes and events, like click or text.

JQuery – A Single Hover Function

As of jQuery 1.4, we can now pass only a single function to the hover method. Before, both the in and out methods were required.

Before

$('#someElement').hover(function() {
// mouseover
}, function() {
// mouseout
});

Now

 $('#someElement').hover(function() {
 // the toggle() method can be used here, if applicable
 });
 

Note that this isn’t an old vs. new deal. Many times, you’ll still need to pass two functions to hover, and that’s perfectly acceptable. However, if you only need to toggle some element (or something like that), passing a single anonymous function will save a handful of characters or so!

JQuery – Keep your Code Safe

If developing code for distribution, it’s always important to compensate for any possible name clashing. What would happen if some script, imported after yours, also had a $ function? Bad stuff!

The answer is to either call jQuery’s noConflict(), or to store your code within a self-invoking anonymous function, and then pass jQuery to it.

Method 1: NoConflict

var j = jQuery.noConflict();
// Now, instead of $, we use j.
j('#someDiv').hide();

// The line below will reference some other library's $ function.
$('someDiv').style.display = 'none';

Be careful with this method, and try not to use it when distributing your code. It would really confuse the user of your script! :)

Method 2: Passing jQuery

(function($) {
// Within this function, $ will always refer to jQuery
})(jQuery);

The final parens at the bottom call the function automatically – function(){}(). However, when we call the function, we also pass jQuery, which is then represented by $.

Method 3: Passing $ via the Ready Method

jQuery(document).ready(function($) {
// $ refers to jQuery
});

// $ is either undefined, or refers to some other library's function.