views:

109

answers:

1

I have this code below which works fine but seems unnecessary as it loops through all div.test even if i never mouse over them. I tried putting the .qTip() function inside the mouseover event to be more efficient but that doesn't seem to work.

Any suggestions on how to make the below code more efficient?

<script type="text/javascript">
    $(document).ready(function () {

        $('div.test').each(function () {

            var tooltipHtml = $(this).next('.tooltip').html();
            $(this).qtip({
                content: {
                    text: tooltipHtml
                },
                style: { width: 450 }
            });
        });
    });
+1  A: 

You can improve it a bit like this:

$(function () {
    $('div.test').each(function () {
        $(this).qtip({
            content: $(this).next('.tooltip'),
            style: { width: 450 }
        });
    });
});

The content option takes a jQuery object (referred to as a jQuery DOM array in the documentation), so there's no need to crawl the HTML for each one. But, if you're still binding a large number of these (hundreds or more) performance still may not be what you're after in older browsers.

Nick Craver