Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Fastest way to show and hide lots of list items

As the user pans around a Google Map, a list of of currently visible markers is updated. This list contains up to 1000 items, and it slows down when several hundred li's are shown or hidden all at once. It's less than half a second, but it's getting annoying.

An array (newLiList) contains the items which should now be visible. Another array (currentLiList) has the items which were previously visible. Both arrays contain the ids of the li's as indexes.

for (var i in newLiList) {
    if (currentLiList[i] != true) {
        $("ul#theList li#"+i).show();
    }
}
for (var i in currentLiList) {
    if (newLiList[i] != true) {
        $("ul#theList li#"+i).hide();
    }
}

Is there a faster way to do this?

like image 302
Chris B Avatar asked Jun 30 '09 22:06

Chris B


People also ask

How hide and show fields in JavaScript?

Style display property is used to hide and show the content of HTML DOM by accessing the DOM element using JavaScript/jQuery. To hide an element, set the style display property to “none”. document. getElementById("element").

How do you display a list in JavaScript?

let list = document. getElementById( "myList" ); Step 3: Now iterate all the array items using JavaScript forEach and at each iteration, create a li element and put the innerText value the same as the current item, and append the li at the list.

How do you hide an array in JavaScript?

In JavaScript, we can hide the elements using the style. display or by using the style. visibility. The visibility property in JavaScript is also used to hide an element.


2 Answers

For every single .show() and .hide() function call, you're causing a redraw in the browser.

Setting the whole list to display none before you change the list items will prevent the browser from having to recalculate the flow of the document every time, and then you could set the list back to block.

Alternatively, if you don't want the flicker of the list disappearing, you could clone the list, make all the items hide that should hide, and then replace the old list with the new.

like image 62
seanmonstar Avatar answered Nov 15 '22 00:11

seanmonstar


You could store the <li> elements in an array directly so you don't have to do hundreds of CSS selector lookups. Then instead of $("ul#theList li#"+i) you just do liArray[i].

FYI, "ul#theList li#<i>" is equivalent to just "#<i>" since element IDs are (supposed to be) unique. You don't need the extra context.

like image 25
John Kugelman Avatar answered Nov 15 '22 00:11

John Kugelman