I have sections with headers. Clicking the header collapses and expands the section below it. A class is also applied or removed to the header for styling purposes. There are 9 of these sections and headers.
$('.header').click(function() {
$(this).toggleClass('open');
$(this).next().slideToggle();
});
Im trying to improve performance for mobile devices. I dont mean page loading times, rather the smoothness of the animation and delay after touching the header before the annimation fires.
Ive read that using IDs is faster than Classes. How much faster will the following be? (note, it would need to be repeated 9 times and ive shown the first 2). Im also assuming using an ID is faster than traversing the DOM with .next(), how much difference will this make?
$('#header1').click(function() {
$(this).toggleClass('open');
$('#section1').slideToggle();
});
$('#header2').click(function() {
$(this).toggleClass('open');
$('#section2').slideToggle();
});
Note, I know its a bit of a crutch but I want to use jQuery not plain JavaScript. The jQuery library will be loaded anyway as its used elsewhere on the site. Thanks
It doesn’t matter at all. While ID lookups are indeed the fastest, modern browsers have optimized selector-based lookups so all of them are pretty fast unless you do something that requires iterating over the whole document (such as a
[someattribute]selector).However,
$('.header')saves you from repeating code and thus is the way to go. Besides that, it’s more readable – in the second example you don’t even know where the element it affects is without looking at the DOM.So, instead of trying to optimize what doesn’t need to be optimized, keep your code clean and maintainable!