Dotol
Dotol

Reputation: 406

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() 

Upvotes: 0

Views: 1949

Answers (2)

000
000

Reputation: 27247

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.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075785

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() {
    // ...
});

Upvotes: 4

Related Questions