0

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

2 Answers 2

4

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() {
    // ...
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, the thing is that I'm using them as anchors for smooth scrolling, my understanding is that you can't use classes as anchors.
@Dotol: You can add classes to a elements, while leaving their hrefs in place as well, and target the class for your click handler. E.g., <a href="#products" class="smooth">...</a>
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.