If you are dealing with hundreds or thousands of elements and need to hide or show them, probably you have already noticed a slow performance. Or you will do. Let's see how to speed up hide()
or show()
in jQuery:
Think again
Double check how are you doing it.
I mean if you are selecting each element by one and then toggling it. Like this:
$('#element1').show();
$('#element2').show();
$('#element3').show();
$('#element4').hide();
...
Please don't use show()
or hide()
in a loop.
If you are doing it, stop. You have to refactor it.
Consider split elements into 2 classes and then apply once. For example:
$('.will-show').show();
$('.will-hide').hide();
How to speed hide() or show() in jQuery
If your code still have bad performance and need to toggle one by one, here is a list of differents ways, slower first:
- Don't use
.toggle()
It's slower than the next method because jQuery has to check if it's visible or not.
- Use
.show()
and.hide()
It's what you are doing. So keep reading!
- CSS vía jQuery
$('#element1').css('display', '');
$('#element4').css('display', 'none')
- Pure CSS in Javascript
items[i].style.display = hideCondition ? 'none' : 'block';
Leave a comment with your doubts or experience