rennacs
rennacs

Reputation: 72

What is the most effecient way to update multiple divs with jQuery

I'm using html5 data attributes to store information about record and create a preview on hover. I'm currently doing the code below but it gets a little sluggish at times. It works, but I'm still learning and know this cant be the best way.

function showfileinfo() {
    var filetags = $(this).attr('data-filetags');
    var tags ='';

    if(filetags.length > 0) {
        $.each(filetags.split(','), function(index, item) {
            tags += '<div>' + item + '</div>';
        });
    }

    $('.tags').html('<div class="tag-image"><img src="/_ima/tag.png"/> tags</div>' + tags);
    $('#file-preview > h3:first').html($(this).attr('data-filetitle'));
    $('.file-name').html($(this).attr('data-filename') + ' - ' + humanize_filesize($(this).attr('data-filesize')));
    $('.description').html($(this).attr('data-filetext'));
    $('#file-preview').hide().fadeIn();

}

I'm updating this preview div.

<div id="file-preview" style="display:none;">
    <h3>Document Title</h3>
    <p class="file-name">acrobat.pdf - 4.06 MB</p>
    <p class="description">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam aliquet arcu nec tortor porttitor laoreet sollicitudin odio vestibulum</p>
    <div class="tags">
        <div class="tag-image"><img src="/_ima/tag.png"/> tags</div>
        <div>wireframe</div>
        <div>visio</div>
        <div>workflow</div>
    </div>
</div>

Upvotes: 0

Views: 280

Answers (1)

powerbuoy
powerbuoy

Reputation: 12838

Every time you change the DOM the browser needs to repaint the page. Which takes time. You should try to never change the DOM more than once (for every change that needs to happen, obviously if you do ajax requests or changes on user interaction you will need to change it again, but for each change you should only change the DOM once).

Also, simply adding element names to your selectors (div.tags rather than just .tags) would also speed things up, and if they're all located in the #file-preview element you should definitely select that first, and then just find() elements from there. That will also speed up a lot.

Upvotes: 2

Related Questions