Skip to content Skip to sidebar Skip to footer

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(){

Solution 1:

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.

Post a Comment for "How To Concatenate Variable And String In Javascript?"