10 Smart jQuery Techniques for Web Developers

jQuery has really overtaken web development with its simplicity, advanced features and plugins. It’s a powerful tool that significantly improves the user‚Äôs interaction with Web applications. With jQuery, you can easily create interesting user-interface in less time, such as: animation, drop down menus, drag elements, page scrolling, popups, dialog and more.

If you have already read our previous article about jQuery Tips and Tricks, to help you improve your skills, in this article we present 10 new, advanced jQuery techniques that will help you improve your skills.

10 Smart jQuery Techniques for Web Developers

1. The DOM Ready Event

The first step to manipulate the DOM element is to subscribe the DOM Ready event. The event is fired when all page elements are present and accessible, so your jQuery selectors will actually return something.

Here is the code to do it:

// the most conventional method we used
$(document).ready(function(){ /* ... */ });

// the shorter jQuery version
$(function(){ /* ... */ });

// and here's a great technique that works everywhere

	alert('DOM Ready!');

function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

In the above technique, we are checking the document.readyState property. If it contains the string in, we set a timeout and check again. Otherwise we execute the passed function.

2. Execute Page Specific JavaScript Code

This is a nice trick to keep your code organized. If you write lots of JavaScript, then it gets difficult to manage, especially when most of your code resides in a single file, which is included in all the pages of your website. Here is a great way to keep to your code in check and avoid too many bugs. Just write a page routing function that executes the JavaScript required for a specific page.

<script type="text/javascript">
var route = {
	_routes : {}, 
	add : function(url, action){
		this._routes[url] = action;
	run : function(){
		jQuery.each(this._routes, function(pattern){

// This will execute only on this page:
route.add('web002.html', function(){

3. Find elements on your page

The more elements your page has, the slower it is to download and render. However, the amount of elements on the page won’t affect your website loading speed too much, but it’s good to check everything once in a while, especially when doing a redesign.

Here is how to do it with jQuery:

<script type="text/javascript">
console.log('Your page has ' + $('*').length + ' elements!');

4. Use the JavaScript logical operator

The JavaScript logical “AND” operator doesn’t evaluate the second expression, if the first is false. You can use this to your advantage and save yourself from having to write a full if-statement:

<script type="text/javascript">
// Instead of this:
	alert("Do here");
// You can write like this:
$('#element').length && alert("Do here");

5. Use the jQuery is() method

You can use the jQuery is() method to check for any matching elements. Actually is() method is more powerful than you might think.

Here are a few examples:

<div id="element"></div>
// First we cache the element into a variable
var element = $('#element');

// Check for div element
element.is('div') && console.log("it's a div");

// Check for div the animate class
element.is('.animate') && console.log("it has the animate class!");

// Animating element

// Check for animation
element.is(':animated') && console.log("it is animated!");
it's a div
it is animated!

6. Define a custom exists() function

You may already know how to check the length of an element to determine whether the element, the selected element, exists or not. You can use the following trick to make your code a bit more expressive and easier to read:

<div id="element"></div>
// Mostly we check like that
console.log($('#elem').length == 1 ? "exists!" : "doesn't exist!");

// The new trick to check element is exist or not
jQuery.fn.exists = function(){ return this.length > 0; }
console.log($('#element').exists() ? "exists!" : "doesn't exist!");

7. Prevent right clicking

You can disable right click to give your web application a more native feel. When a right click occurs, browsers emit the contextmenu event and as with any other event, you can listen for it, and call the preventDefault() method.

Here is the trick:


8. Break out of iframes

You have probably noticed on a few websites, which show your site with their bar on top of the page. This is done by including your page in an iframe.

Here is how to break out of it:

if(window != window.top){
	window.top.location = window.location;

You just need to compare the window object of your page, to window.top. Normally, they are the same object, but if your site is being shown in an iframe, they will differ. Then you simply redirect the browser directly to your site.

9. Prevent text from being selectable

Sometimes you need to prevent text on the page from being selectable. This technique is useful when building interfaces, which can be dragged or reordered, as you don’t want users to select text from the page by accident. Here is code that does this and works in all current browsers:

$('p').attr('unselectable', 'on')
	  .css('user-select', 'none')
	  .on('selectstart', false);

10. Efficient jQuery selectors

Every time you construct a new jQuery object by passing a selector, the engine, traverses the DOM and matches the selector to real elements. This is slow when done with JavaScript, so you should cache the jQuery object in a variable if you need to use the same set of elements multiple times to prevent DOM traversing each time.

var $p = $("p");
$p.css("color", "blue");
$p.text("Text changed!");

Related posts:

By admin

Robert is a web designer and online marketing expert with over 18 years of experience. Twitter, Facebook, Google+, or even by subscribing to our RSS Feed.