Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimize Jquery with loops

Tags:

jquery

loops

I have this code:

            $('.counter_d').mouseover(function() {
                   $('#description').html('Counter');
             });
            $('.selector_d').mouseover(function() {
                   $('#description').html('Selector');
             });
             $('.date_d').mouseover(function() {
                   $('#description').html('Date');
             });

and several more, but I think the file could be smaller and even reusable using loops, but I'm not able to bind the description (HTML method) with the selector.

I want to use something like this:

              var selectors=['.counter_d','.selector_d','.date_d'];
              var description=['Counter', 'Selector', 'Date'];


              for(var i=0; i<selectors.length; i++)
                 $(selectors[i]).mouseover(function() {
                   $('#description').html(description[i]);
                 });

Any help? Thanks

like image 779
Frank Avatar asked Dec 27 '22 18:12

Frank


2 Answers

var selectors = {
    '.counter_d': 'Counter',
    '.selector_d': 'Selector',
    '.date_d': 'Date'
};


$.each(selectors, function (key, value) {
    $(key).mouseover(function () {
        $("#description").html(value);
    });
});

Example: http://jsfiddle.net/andrewwhitaker/bS28q/

like image 65
Andrew Whitaker Avatar answered Dec 29 '22 09:12

Andrew Whitaker


The problem is the variable i is assigned to 3 at the time the mouseover callback is executing.
As description[3] is undefined no new HTML is assigned.
Fiddle enable your browser console to read the console.log!

I think a more elegant solution is to give the HTML elements an extra attribute description and in the mouseover callback simply do:

$('#description').html($(this).attr("description"));

(You see it in the fiddle above)

In my opinion you can even select all elements in a more elegant way and get rid off the loop as jQuery will handle this for you:

$(".counter_d, .selector_d, .date_d").mouseover(function() {
    $('#description').html($(this).attr("description"));
});

updated Fiddle

like image 33
nuala Avatar answered Dec 29 '22 09:12

nuala