Awesome jQuery Tips & Tricks

jQuery is first choice of a large number of web developers. jQuery earned this fame because of its ultimate powers to perform complex tasks in a simple manner. Thats why it is said about jQuery – ‘write less do more’. Let’s unleash some extremely powerful features of jQuery that can be to help you in web development.

Open Blank Pages on Clicking Hyperlinks

XHTML 1.0 Strict don’t allow target=’_blank’ attribute of anchor tag. A good solution to this problem should be using jQuery to make links opening in new windows:

$('a[@rel$='external']').click(function(){ = "_blank";

<a href="" rel="external"></a>

Find all Matched Elements


Image Preloading

It is good to preload images with jQuery al places where you want to show large number of images. Follwoing tip can be useful to you:

jQuery.preloadImages = function()
for(var i = 0; i").attr("src", arguments[i]);

// Usage
$.preloadImages("image1.gif", "/path/to/image2.png", "some/image3.jpg");

Know your Browser

CSS usage can be different for different browsers. Now you need not write conditional comments for different browsers in your CSS code. See how jQuery helps you out:

//A. Target Safari
if( $.browser.safari ) $("#menu li a").css("padding", "1em 1.2em" );

//B. Target anything above IE6
if ($.browser.msie && $.browser.version > 6 ) $("#menu li a").css("padding", "1em 1.8em" );

//C. Target IE6 and below
if ($.browser.msie && $.browser.version <= 6 ) $("#menu li a").css("padding", "1em 1.8em" );

//D. Target Firefox 2 and above
if ($.browser.mozilla && $.browser.version >= "1.8" ) $("#menu li a").css("padding", "1em 1.8em" );

Disable Right-Click Contextual Menu

Disabling right-clicks is much easier with jQuery:

return false;

Adding & Removing CSS classes from Eelements

//Adding a class

//Removing a class

Check if a Specific Element has a CSS Class

You can easliy know if a particular element has used a CSS class or not:


Switch CSS stylesheet using jQuery

Not only CSS classes but complete CSS file can be changed with jQuery. See how it is done:

$('link[media='screen']').attr('href', 'Alternative.css');

Check if an element exists

if ($('img').length) {
log('We found img elements on the page using "img"');
} else {
log('No img elements found');

Get the parent/sibling element of an element

//Know the parent
var id = $("button").closest("div").attr("id");

//Know the Siblings

Remove an option from a select list

$("#selectList option[value='2']").remove();

Get the selected option as text

$('#selectList :selected').text();

Apply a “zebra” effect on tables


Count children of an element

$("#foo > div").length

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.


2 thoughts on “Awesome jQuery Tips & Tricks

Comments are closed.