jQuery and CSS Selectors: Part 5


Introduction

In this post you are going to learn all about jQuery and CSS Selectors, if you are still not using jQuery in your web apps, this post will motivate you.

Here I am going to talk on "Custom Selectors" and filter expression, let's first look at a problem that we will solve in this article.

Problem

Assume I have a blog/website and I want all external URLs to open on new browser tab. For example when you click on any external URL on Facebook, it opens URL on new tag. No meaning you have mentioned "target" attribute with URL or not, I always want external URLs to open on new tab.

In addition with this, I also want to add an external icon with all external URLs. How to do this?

Look at the image and demo given below that is fully functional solution.

Demo Page

image001.jpg

I guess you can understand my ideas now. In above image/demo you can see, my blog URLs has no icon and it always opens on same page (not on new tab), rest all URLs will open on new tab.

Now to develop such functionality we need to take the advantage of jQuery's "Custom Selectors" and filter method. So, let's learn both of them.

Filter Expression

It reduces the set of matched elements to those that match the selector or pass the function's test.

Remember filter is big topic and I am not going to discuss all here. If you want to learn more, visit here.

Example

In Part 4, we have learnt many things including "Odd and Even Custom Selectors", taking example from that part.

In that post, I used following code to add "alt" class to all even rows:

$('tr:even').addClass('alt');

And now, we are aware about "filter", so we can achieve same using "filter" also, here's how:

$('tr').filter(':even').addClass('alt');

Code Snippets

image002.jpg

Download the attached project, if you can't see clear code in image above.

In above jQuery, I have used some keys, let's talk on them.

this.hostname

This will get current host name (domain).

location.hostname

This will get target host name (domain).

event.preventDefault

If this method is called, the default action of the event will not be triggered.

event.stopPropagation

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

In the next post, I will continue my talk on jQuery Selectors. I hope you like it. Thanks.


Similar Articles