RSS

Creating Custom Selector in JQuery

27 May

JQuery custom selectors are very powerful. This allows you to write custom selectors that are fulfilling needs for your script domain. This makes repetitive complex selector logic much intention revealing and more succinc.
Custom selectors are just like other selectors that selects DOM elements with criteria defined by yourself. Most of the time they just allows you to write more succinct code that will enhance code reuse.
Say if you want to select hyperlinks that point to pdf files and give indication of them with icon you can achieve it with CSS selectors. Particular CSS that is used are indicated below.
jquery custom selector

• Please note for demo purpose I have not spent much time formatting the page

a[href $='.pdf'] { 
background: url("../Images/pdf-icon.jpg") no-repeat scroll right center / 20px auto rgba(0, 0, 0, 0);   
padding-right: 30px; //this padding will universally accommodate the pdf icon
}
 

For above code browser support is not bad either according to here. http://www.quirksmode.org/css/selectors/
However for demo purpose regarding custom JQuery selectors I am achieving the same using JQuery which is however not the better way but I saw that I had used it for one of my old project which I saw when I was doing maintenance fix.

jQuery.noConflict();

(function($) {
	$.extend($.expr[':'], {pdfLinks : function(o) {
		if (typeof o.href !== "undefined") {
			var link = o.href;
			return link.indexOf("pdf", link.length - 3) !== -1;
		}
		return false;
	}});
	
	$("a:pdfLinks").addClass('pdfIcon');
})(jQuery);
.pdfIcon {
	background: url("../Images/pdf-icon.jpg") no-repeat scroll right center / 20px auto rgba(0, 0, 0, 0);
	padding-right: 30px;
}

It is that $.extend does the job of extending JQuery to use the custom selector. In above CSS class we give additional padding of 30px to the right of the selected links so that there is a space to include background pdf icon.

Advertisements
 
Leave a comment

Posted by on May 27, 2014 in Javascript, jQuery

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: