J_LIU J_LIU - 11 days ago 5
jQuery Question

Looping in JQuery is not doing what I want it to

I created a function so that when user hovers over an image, the image opacity lowers and the visibility of text becomes visible and not hidden. I used loops to apply this functionality for multiple classes, but the looping isn't doing what I want it to do. I am not sure why.

This is what I want it to do

$(document).ready(function(){

var classes = [".col0",".col1", ".col2", ".col3", ".col4", ".col5", ".col6", ".col7", ".col8"]

$(classes[0]).hover(function(){
$(classes[0]).css("opacity", "0.5");
}, function(){
$(classes[0]).css("opacity", "1");
});
$(classes[1]).hover(function(){
$(classes[1]).css("opacity", "0.5");
}, function(){
$(classes[1]).css("opacity", "1");
});
..... And continue until it finishes all the variables
});


I tried using loops like this. The above solution works, but it is a lot of repetition so I want to use loop, but loop does not work.

$(document).ready(function(){

var classes = [".col0",".col1", ".col2", ".col3", ".col4", ".col5", ".col6", ".col7", ".col8"]

for(i = 0; i < 8; i++){
$(classes[i]).hover(function(){
$(classes[i]).css("opacity", "0.5");
}, function(){
$(classes[i]).css("opacity", "1");
});
}
});

Answer

You know, jQuery accepts multiple elements as a selector, just as $(".col1, .col2") etc etc - so do that. Convert your array to a string list and go from there:

var classes = [".col0",".col1", ".col2", ".col3", ".col4", ".col5", ".col6", ".col7", ".col8"]
var selector = classes.join(",");

$(selector).hover(function(){
    $(this).css("opacity", "0.5");
}, function(){
    $(this).css("opacity", "1");
});

Using an instance of this - you'll be able to get the current element being hovered and do what you need.

Comments