By default, the jQuery selectors are pretty advanced. You can select items by classes, ids, attributes, the first, the last, etc… But why stop there? By simply extending jQuery, we can add our own custom selectors to further enhance how we use jQuery. In this example, I will create an extended function called widthOver300 leveraging jQuery's $.extend
Let's begin by looking at a basic, pre-existing, jQuery selector:
In the above code example, I am toggling the first element that jQuery finds with the class name of myClass. This will either show or hide the element based on it's current display CSS property.
Now, what if I want to find an element with the name of myClass that has a width of over 300 pixels? It would be nice to do something like this:
This can be accomplished with a nice little jQuery extension as follows:
With the above code added, if I re-run the previous example, all elements with the class name of myClass that have a width of more than 300 pixels will be toggled on or off.
By extending jQuery, you can add custom selectors to help make your code more readable and reusable. Simply be sure to check jQuery first so that selector doesn't already exist as you wouldn't want to reinvent the wheel! Published on Mar 16, 2019 Tags: extend
| JavaScript
| jQuery Tutorial
Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article
that you just finished reading.
No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner
or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in
and improve your skillset with any of the tutorials below.
Reviewing jQuery's toggle
$(".myClass:first").toggle();
Creating a jQuery selector
$(".myClass:widthOver300").toggle();
$.extend($.expr[":"], {
widthOver300: function (e)
{
return $(e).width() > 300;
}
});
Related Posts
Tutorials
Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.