Selected 20 jQuery Tips & Tricks

1. Setting the context and improve performance

On the core jQuery function, specify the context parameter when. Specifying the context parameter allows jQuery from a deep branch in the DOM, and not from the root DOM. Given the large enough DOM, specifying the context parameter should result in performance improvements....

$("input:radio", document.forms[0]);

2. Line breaks and chainability

Instead of doing:

$("a").hide().addClass().fadeIn().hide();

You can increase readability like so:

$("a")
  .hide()
  .addClass()
  .fadeIn()
  .hide();

 3. Checking the Index

jQuery's. Index, but it is a pain as you need to use a list of elements and element of the index you want to pass

var index = e.g $('#ul>li').index( liDomObject );

The following is easier:

if you want to know the index of an element within a set, e.g. list items within a unordered list:



$("ul > li").click(function ()
{
    var index = $(this).prevAll().length;
});

4. Use the jQuery data method

jQuery method data () is useful and not well known. It allows you to bind data to DOM elements without modifying the DOM.

5. Optimize the performance of complex selectors

Consult a subset of the DOM using selectors complex dramatically improves the performance:

$("#myButton").click(function() {
         $("#myDiv").fadeTo("slow", 0.01, function(){ //fade
             $(this).slideUp("slow", function() { //slide up
                 $(this).remove(); //then remove from the DOM
             });
         });
});

6. Fadeout slideUp effect of removing an element

Combine more than one effects in jQuery to animate and remove an element from DOM.
$("#myButton").click(function() {
         $("#myDiv").fadeTo("slow", 0.01, function(){ //fade
             $(this).slideUp("slow", function() { //slide up
                 $(this).remove(); //then remove from the DOM
             });
         });
});

7. Check if an element exists

Use following code to check if an item exists or not.

if ($("#someDiv").length) {
    //hooray!!! it exists...
}

8. Add dynamically created elements in the DOM

Use following code to create a DIV dynamically and add it to the DOM. Read more:

var newDiv = $('
'); newDiv.attr("id","myNewDiv").appendTo("body");

9. Live Event Handlers

Set an event handler for any element that matches a selector, even if added to DOM after the initial page load:

$('button.someClass').live('click', someFunction);

This allows you to load content via ajax, or add them via javascript and event handlers have been configured properly for these items automatically. Similarly, to stop the live event handler:

$('button.someClass').die('click', someFunction);

These event handlers live some limitations compared to regular events, but they are very good for most cases. Live Event working from jQuery 1.3

10. Creating custom selectors


$.extend($.expr[':'], {
    over100pixels: function(a) {
        return $(a).height() > 100;
    }
});
 
$('.box:over100pixels').click(function() {
    alert('The element you clicked is over 100 pixels high');
});

11. Cloning an object in jQuery

Use .clone() method of jQuery to clone any DOM object in JavaScript.

// Clone the DIV
var cloned = $('#somediv').clone();

jQuery method clone () does not clone a JavaScript object. To clone JavaScript objects, use the following code.



// Shallow copy
var newObject = jQuery.extend({}, oldObject);
 
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

12. Check if something is hidden using jQuery

We use .hide(), .show() methods in jquery to change the visibility of an element. Use following code to check the whether an element is visible or not.

if($(element).is(":visible") == "true") {
       //The element is Visible
}

13. Selecting an element with . (period) in its ID

Use backslash in the selector to select the element having period in its ID.
$("#Address\\.Street").text("Enter this field");

14. Counting immediate child elements

If you want to count all the DIVs present in the element #foo
<div id="foo">

<div id="bar">

</div>

<div id="baz">

<div id="biz">

</div>

</div>
//jQuery code to count child elements
$("#foo > div").size()

15. Make an element to “FLASH”


jQuery.fn.flash = function( color, duration )
{
    var current = this.css( 'color' );
    this.animate( { color: 'rgb(' + color + ')' }, duration / 2 );
    this.animate( { color: current }, duration / 2 );
}
//Then use the above function as:
$( '#importantElement' ).flash( '255,0,0', 1000 );

16. Center an element on the Screen


jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}
 
//Use the above function as:
$(element).center();

17. Alternate way of Document Ready

//Instead of
$(document).ready(function() {
    //document ready
});
//Use
$(function(){
    //document ready
});

18. Getting Parent DIV using closest

If you want to find the wrapper DIV element (regardless of that DIV ID), then you'll want this jQuery selector:

$("#searchBox").closest("div");

19. Get mouse cursor x and y axis

This script will display the value of x and y - the coordinates of the mouse pointer.

$().mousemove(function(e){
    //display the x and y axis values inside the P element
    $('p').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});

20. Disable right-click contextual menu

There are many available JavaScript snippets to disable right-click context menu, but jQuery makes things much easier:
$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
});

Post a Comment

1 Comments

  1. wow amazing this information is rock.....thanks for providing these solution....
    jics tech uae

    ReplyDelete

Thank you for your comment.. We will contact you soon..

Emoji
(y)
:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:P
:o
:>)
(o)
:p
(p)
:-s
(m)
8-)
:-t
:-b
b-(
:-#
=p~
x-)
(k)

Close Menu