0

If I were to bind a click event to a lot of different selectors using jQuery like the following:

scrollToPoint('.main-nav a, .sub-nav a, .enquire-btn, #showcase-list a, #showcase-more-info a.back-btn')

What is the industry standard method to lay this out syntactically and is their an alternative approach?

Thomas
  • 523
  • 2
  • 9
  • 23
  • 8
    Best approach is that you can have the same class for all the element that you want to select. – Aravind Sivam Oct 14 '14 at 11:00
  • possible duplicate of [JQuery same click event for multiple elements](http://stackoverflow.com/questions/1313373/jquery-same-click-event-for-multiple-elements) – Nirav Gandhi Oct 14 '14 at 11:03
  • @NiravGandhi That's no duplicate. The OP evidently knows *how* to target multiple elements. – George Oct 14 '14 at 11:03
  • possible duplicate of [Best Practices For Writing jQuery Selectors](http://stackoverflow.com/questions/13016542/best-practices-for-writing-jquery-selectors) – Rahul Singh Oct 14 '14 at 11:05
  • 1
    Clearly not a duplicate if you actually read my question. Thanks Aravind Sivam, you make a good point! – Thomas Oct 14 '14 at 11:07

2 Answers2

2

I think this is the best approach IF YOU ARE SURE YOU WANT THAT MUCH SELECTORS:

var selectors = [
    ".main-nav a",
    ".sub-nav a",
    ".all",
    ".other",
    ".selectors"
];

scrollToPoint(selectors.join(', '));

function scrollToPoint(sel){
  $('#selectors').text(sel);  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="selectors"></div>
Andreas Furster
  • 1,558
  • 1
  • 12
  • 28
0

Selector optimization is less important than it used to be, as more browsers implement document.querySelectorAll() and the burden of selection shifts from jQuery to the browser. Came from jQuery's official site.

Giannis Grivas
  • 3,374
  • 1
  • 18
  • 38