'jQuery multiple target IDs for click function
This may be a little redundant but I was wondering if there's a way to improve the code by shortening it to avoid repetition.
$('a[href*="#about"]').click(function()
I want to target #about
#products
#process
#gallery
#contact
I want to avoid:
$('a[href*="#about"]', 'a[href*="#process"]', a[href*="#etc"]' ).click(function()
Solution 1:[1]
Give them all a class and target that:
$(".the-class").click(function() {
// ...
});
If you can't do that, then what you want to avoid (but done correctly) is what you need to do:
$("[href=#about], [href=#products], [href=#process], [href=#gallery], [href=#contact]").click(function() {
// ...
});
Solution 2:[2]
Alternatively you can set up a single click handler on the page, and delegate based on which element was clicked.
var handledHrefs = ['#about', '#products', '#process', '#gallery', '#contact'];
$('body').on('click', 'a[href^=#]', function (e) {
if (handledHrefs.includes(e.target.attr('href'))) {
// ...
}
});
This actually has a better performance than attaching individual event handlers, surprisingly enough.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | T.J. Crowder |
Solution 2 | Joe Frambach |