loading...

Neat and Easy to Use jQuery Examples

wpgaurav profile image Gaurav Tiwari ・2 min read

jQuery is the most popular JavaScript library in use today. It gives web developers a great relief by abstracting away the complex tasks of traversing the DOM, creating elements, handling events and much more. Many people search for some amazing and simple jQuery tutorials on the web. Here I will show you some simple jQuery tutorial which helps you a lot.

1)Disable right click option (jQuery tutorial)

If you want to disable the right click option (context menu) on a webpage in your browser then you can use this small jquery trick.

$(document).ready(function(){
$(document).on(“contextmenu”,function(e){ e.preventDefault(); });
});

The code above listens for contextmenu event, and calls the preventDefault() method.

2)Define an exists function (jQuery tutorial)

If you want to check, if element exists or not then you can use this small jquery trick also.
There are two ways to check if element exists:

//old way :
console.log($(‘#element’).length == 1 ? “exists!” : “doesn’t exist!”);
//new trick:
jQuery.fn.exists = function(){ return this.length > 0; }
console.log($(‘#element’).exists() ? “exists!” : “doesn’t exist!”);

In both tricks you can use length property and a ternary conditional statement. But the second way is more useful than the first because you can extend jQuery with your own functions and you can use exists() function normally as you can use other functions in jQuery.

3)Find external links and Mark them (jQuery tutorial)

In this example, I will show you how to mark external links with text “external link” using jquery.

HTML

<ul id=”Links”>
<li><a href=”index.html”>Home</a></li>
<li><a href=”./cat.html”>Category</a></li>
<!– External Link: –>
<li><a href=”http://www.google.com/”>Google</a></li>
</ul>

jQuery

$(document).ready(function(){
// Loop through all the links
$(‘#Links a’).each(function(){
if(this.hostname != location.hostname){
// The link is external
$(this).append(‘<span> – (External Link)</span>’).attr(‘target’,’_blank’); }
});
});

The code above will loop through all the links and checks if the link’s hostname is equal to the website’s hostname, if the hostname of link is not equal to the hostname of the website. Then the link is marked as an external link.

Posted on by:

wpgaurav profile

Gaurav Tiwari

@wpgaurav

Blogger at gauravtiwari.org / Developer / Designer

Discussion

markdown guide
 

Lol. This draft was laying unused in my google docs, thought it'd be better to post it.