Clonkex
Clonkex

Reputation: 3637

How to concatenate variable and string in JavaScript?

Please don't immediately mark this as a duplicate. I've looked at similar questions but still can't figure this out.

This is what I have currently:

$(document).ready(function(){
    for(var i=1;i<2;i++)
    {
        $("#MenuBarButton"+i).mouseover(function(){
            $("#ldheMenuBarLayer"+i).stop().animate({height:'66px'},{queue:false, duration:600, easing: 'easeOutBounce'})
        });
        $("#MenuBarButton"+i).mouseout(function(){
            $("#ldheMenuBarLayer"+i).stop().animate({height:'41px'},{queue:false, duration:600, easing: 'easeOutBounce'})
        });
    }
});

That doesn't work. Nothing happens and nothing appears in the console. But if I directly replace the i with a 1 in each of the $ function things it works.

I'm not new to programming but I'm new to JavaScript, so am I doing something obviously wrong? Thanks!

EDIT: When I say I replace the i with a 1, that's because the IDs are MenuBarButton1 and ldheMenuBarLayer1.

Upvotes: 1

Views: 2670

Answers (1)

lonesomeday
lonesomeday

Reputation: 238085

The basic problem you have is that there is only ever one value for i. That variable only exists once. The code inside the event handler points to the variable, not to its value when the event handler was created. So take your code that looks like this:

$("#ldheMenuBarLayer"+i).stop()...

Every time the event handler is run, i will be 2, because we've already gone all the way through the loop.

You need to use the value of i, not a reference to the variable. You do this by introducing a new scope with an anonymous, immediately-invoked function:

for(var i=1;i<=2;i++)
{
    (function(j) {
        $("#MenuBarButton"+j).mouseover(function(){
            $("#ldheMenuBarLayer"+j).stop().animate({height:'66px'},{queue:false, duration:600, easing: 'easeOutBounce'})
        });
        $("#MenuBarButton"+j).mouseout(function(){
            $("#ldheMenuBarLayer"+j).stop().animate({height:'41px'},{queue:false, duration:600, easing: 'easeOutBounce'})
        });
    }(i))
}

Leaving aside all of this, it's worth mentioning that this isn't a very jQuery-ish way of going about things. The jQuery way might look like this:

var menuBarButtons = $('.menuBarButton').mouseover(function() {
    var idx = menuBarButtons.index(this);

    $('.ldheMenuBarLayer')
        .eq(idx)
        .stop()
        .animate(
             {
                 height: '66px'
             },
             {
                 queue: false,
                 duration: 600,
                 easing: 'easeOutBounce'
             }
         );
});

This code won't work (probably). It needs to be based on your markup and page structure. It might ultimately not be possible.

Upvotes: 2

Related Questions