1

I'm working with this function, but it doesn't work correctly: only the last element works.

Here is my JavaScript code:

function hover_action() {

    var array = ["elem1","elem2","elem3","elem4"];

    $(array).each(function( index, value ) { 
        value1 = "#box-" + value + " img";
        value2 = "div#name-" + value;
        $(value1).hover(function(){
            $(value2).fadeIn(300);
        }, function(){
            $(value2).fadeOut(300);
        });
    });
}

Her is my HTML code:

<div>
    <div id="box-elem1"><img src="path1" /></div>
    <div id="name-elem1"><span>NAME 1</span><div>
</div>
<div>
    <div id="box-elem2"><img src="path2" /></div>
    <div id="name-elem2"><span>NAME 2</span><div>
</div>
<div>
    <div id="box-elem3"><img src="path3" /></div>
    <div id="name-elem3"><span>NAME 3</span><div>
</div>
.
.
.

Thanks for your help.

3
  • 6
    not a good idea to bind event in a loop which is called in a function. Commented May 25, 2016 at 10:02
  • There is no way for us to asses why it's not working without some relevant html Commented May 25, 2016 at 10:17
  • You are defining value2 (and value1 btw but doesn't really matter here) as global, that's why. Use var statement: var value2 = "div#name-" + value; Commented May 25, 2016 at 10:21

3 Answers 3

2

Try something similar:

$('div[id^="box-"]').hover(function(){
            $(this).next('div[id^="name-"]').fadeIn(300);//asuming the next element is the element you want to hover
        }, function(){
            $(this).next('div[id^="name-"]').fadeOut(300);
        });

And for god's sake use classes

demo

Sign up to request clarification or add additional context in comments.

Comments

1

I would suggest you this:

var $els = $("#elem1, #elem2, #elem3, #elem4");

$els.hover(function() {
  $("div#name-" + this.id).fadeIn(300);
}, function() {
  $("div#name-" + this.id).fadeOut(300);
});

Comments

0

the correct solution was by Izumi, but his/her answer has disappeared from this thread (?)

function hover_action() {

    var array = ["elem1","elem2","elem3","elem4"];

    $.each(array,function( index, value ) { 
        value1 = "#box-" + value + " img";
        value2 = "div#name-" + value;
        $(value1).hover(function(){
            $(value2).fadeIn(300);
        }, function(){
            $(value2).fadeOut(300);
        });
    });
}

thanks to Izumi...

The reason why OP code is not working is because of wrong use of selector. In JQuery, $() is element selector which aim at DOM object. array is javascript variable so it is not working. $.each is the correct way to iterate through javascript variable.

Reference from JQuery: jQuery.each()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.