jQuery tips and tricks

jquery-logo-x

Level: intermediate

In today’s article we’ll do a small review of interesting jQuery tips. The framework itself gives the programmer a gigantic possibilities, that still can be extended through tricks and best practices.

jQuery tips

This time we focus more on practice and examples, rather than theory.

Tip 1. Determine the size of our document

In details, it’s a query of the DOM elements number, which the page contains. In jQuery this information is available in the following manner:

alert($('*').length);

2. Checking if a checkbox is checked 🙂

It’s simple – can be done in such a way:

if ($("#myCheckBoxID").is(':checked')) {
  ...
}

or by checking an attribute:

if ($('#myCheckBoxID').attr('checked')) {
  ...
}

3. Checking whether an element exists

if ($("#myElementID").length == 0) 
    alert('#myElementID does not exist');
else
    alert('#myElementID exist!');

4. Checking if an element is visible

Is visible:

$("#myElementID").is(":visible");

Is hidden:

$('#myElementID').is(':hidden')

5. Number of found (matching) elements

This simple trick gives us information of how many elements of the document matches the selector (e.g. find by the CSS class):

alert($(".our-class-css").size());

6. Scroll the page to the selected item

How to scroll the page in jQuery? Simply:

$(document).scrollTop($('#myElement').offset().top);

7. Substitution of one element to another

So replace an element by another:

$("#oldID").replaceWith("<span>New element ...</span>");

8. Finding an element by CSS class

The code below adds blue 2px border for all elements with foobar class.

$('body').find('.foobar').css({'border': 'solid 2px blue'});

9. Finding an element by attribute

Going one step further, we can search for an item by attribute, even our own.

var p_id = 12345;
$('#container').find('div[data-photoid="' + p_id + '"]').hide();

// e.g.:
// <div data-photoid="12345"><img src="path-to-image.jpg" /></div>

This code is looking for a specific item (here: div), wherein the attribute data-photoid has a value of the specified variable (p_id), and hides the item if was found.

10. “Sticking” actions to the HTML elements

First, we call the unbind() function, so we’ll be able to connect behavior defined by us to the component, instead of the default.

HTML

<span id="prev">PREV</span> 1 2 3 4 5 <span id="next">NEXT</span>

JS

$('#next').unbind();
$('#prev').unbind();

$('#next').click(function() {
    clickTime = new Date().getTime();
    alert(clickTime);

    return false;
});

$('#prev').click(function() {
    clickTime = new Date().getTime();
    alert(clickTime);

    return false;
});

In this example, the time of click is displayed (timestamp).

Next tricks in jQuery are not directly related to the document element.


11. Blocking the right mouse button in jQuery

$(document).bind("contextmenu", function(e) {
    return false;
});

12. Short version of document.ready

For the document.ready event

$(document).ready(function() {
    ....
});

we can use shorter version:

$(function() {
    ...
});

13. Reaction to resize the browser window

Simply we handle the resize event of the window. We can thus adjust the size or appearance of the elements depending on the window size.

$(window).resize(myHandler);

function myHandler() {
    alert('Do something ...');
}

14. More?

Take a look at the pages dedicated to jQuery and JavaScript tricks, such as:

http://css-tricks.com/snippets/jquery/

I also recommend a topic on StackOverflow – a collection of interesting solutions:

http://stackoverflow.com/questions/182630/jquery-tips-and-tricks

jQuery tips – summary

The jQuery Framework gives the power for developers, especially when we know the tricks and tips.

Everything that can increase our capacity or to save time, should always be welcome.

Web and Mobile Software Developer, with years of experience. My biggest passions are programming, new technologies, e-commerce, as well sports, cars, and of course my family.

Facebook Twitter LinkedIn Google+ Skype Xing 

Share: Share on Facebook0Tweet about this on TwitterShare on Google+1Share on LinkedIn3Share on Tumblr0Digg thisEmail this to someonePin on Pinterest1
You can leave a response, or trackback from your own site.