Many people have asked me how easy it is to create a jQuery plugin so I thought I’d have a go at trying to explain it, I hope this makes sense.
I am presuming you know the basics about setting up jQuery on your page and how to include a javascript file.
Step 1
Firstly create a new javascript file (advanced javascript users can code this within their current javascript pattern, although advanced javascript users probably wont be reading this, am I still talking?) call the file something relevant to your plugin, in this example we will call it external.jquery.js, this file needs to be called after the jquery library file:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="external.jquery.js"></script>
Step 2
No you can begin to build the plugin, within the external.jquery.js file setup the self invoking function:
(function($){
//code in here
})(jQuery);
Step 3
Now you need to add the function extension so calling your function will work, we will call our extension plugin externalLinks:
(function($){
$.fn.externalLinks = function(){
//function routine here
}
})(jQuery);
Step 4
We can now add our routine to the function, this can be what ever you want to do, in our example I will check for a rel attribute with a value of external and if present then add on a target=”_blank”, obviously you can do what ever you want:
(function($){
$.fn.externalLinks = function(){
//loop through the selected dom elements
this.each(function(i,obj){
//find the anchors tags within
$anchors = $(obj).find("a").get();
$.each($anchors, function(j,ele){
//if external rel set target _blank
if (ele.rel == 'external'){
ele.target = '_blank';
}
});
});
}
})(jQuery);
Step 5
All that’s left to do now is tell the function which elements you want to run the external links function on, to do this you need to put in a separate call using the jquery selector call shown below:
$('body').externalLinks();
That’s it, the above snippet will run the external links function on all links with the body tag. Here is our example external links plugin.
February 21, 2012 at 9:33 am Hello, I inemelpmted your code into my web projcet but the problem is, when Contents start to slide they dont stop untild the end????what could the problem be???I could not find
This jQuery plugin is a basic plugin to change anchor tags to launch in new window, I just used this as an example, you issue seems to be related t a specific implementation of this plugin so you would have to provide more details for me 🙂