× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Example of a jQuery Plugin

Jacob Heater
Nov 12, 2016
<p>This is just a quick example of how to extend jQuery by writing a plugin. When extending jQuery, you can either add a function to the jQuery function itself, or you can add a function to the jQuery fn namespace. Adding a function to the jQuery function itself will not extend any instances of jQuery.fn.init, rather, you would access those functions in the jQuery namespace. If you extend jQuery.fn, all instance of jQuery will be extended. Therefore, with our plugin example below, all instances of jQuery will now have the getSelectedValue function. </p> <p> </p> <pre><code class="language-javascript">(function($) { /** * Returns the value of the selected option if the element is a select * element, otherwise, it just returns the default value of $.fn.val(). * * @returns {String} The value of the selected option, or $.fn.val(). */ $.fn.getSelectedValue = function() { if (this.is("select")) { //This is a select element. //Let's find the selected option. return this.find("option:selected").val(); } else { //This is not a select element. Return the value. return this.val(); } }; })(jQuery); //Usage example var ddwnVal = $(".dropdown").eq(0).getSelectedValue();</code></pre> <p>As you can see in the example above, I have used the .dropdown selector, and we can now call our getSelectedValue function. I hope this was informative. Thanks for reading!</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus