We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
JQuery has simplified a lot of my day to day coding. I think it is an amazing little framework and apparently a lot of people do too. Even Microsoft is bundling it with its ASP.NET MVC framework which , as far as I know, a first for open source software. Beyond even handling all the all of the cross browse mess, my favorite part of jQuery is the ability to easily extend the framework through plug-in. That brings us to the topic for this post. We are going to look at how easy it is to create a plug-in for jQuery.
For this post I want to pick something that is fairly simple yet demonstrates the power of plugins. For this post I am going to show you how to create a plug-in that will highlight keywords in a given block of text. Many websites use something similar when performing searches.
A good guideline to follow when creating the file for your plug-in is use the following convention: jquery.pluginName.js. Keeping this in mind lets create a file called jquery.hightlight.js. Now in our main HTML file we should have something like the following.
In jquery.highlight.js we will create the shell of our plug-in.
In the above code we are passing the jQuery object into our plug-in so we can extend it. It is recommend that you use jQuery instead of $ to avoid conflicts with other libraries.
Plugins always extend the fn object of jQuery as you can see where we created $.fn.highlight. Next we created a defaults object which we will fill out later on and then merge the defaults with the passed in options. On the next line we check to see of the words object is a string. If it is we turn it into an array. This way the plug-in will accept a single word as a string or an array of words to be highlighted. Finally, we return the this object which contains all the elements that jQuery found that met the selector we used. Before the plug-in returns it loops over each of the found elements so we can do our highlighting on them.
Using the shell we created above we can create the code that does the highlighting. First lets define our default values in case there aren’t any options passed into the plug-in.
Now let’s highlight our words.
This is pretty simple. We are looping through each of our words. We are wrapping the words in a span tag that uses CSS to define a background and foreground color. Then we simply do a find and replace on the elements innerHTML. It is that easy. You can see a demo of this plug-in our freebies page. Stay tuned for more great posts from Dev102.com by grabbing the RSS feed. You can also see more posts I have written on my blog or grab my RSS feed.
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd