If Statements Skipping or Evaluating Strangely, JavaScript and jquery

Posted by tlm2021 on Stack Overflow See other posts from Stack Overflow or by tlm2021
Published on 2010-05-27T17:54:13Z Indexed on 2010/05/27 18:01 UTC
Read the original article Hit count: 200

Filed under:
|

So in jQuery, I have a global variable "currentSubNav" that stores a current visible element. The following code executes on "mouseenter".

I need it to get store element's ID, check to see if there was one. If there wasn't, set the new visible element to the default.

$('#mainMenu a').mouseenter(function() {
    var newName = $(this).attr("id");
    if(newName == ''){
        var newName = "default";
    }

Then it checks to see if the new element matches the current one. If so, it returns. If not, it performs the animations to bring in the new one.

    if(newName == currentSubNav){
     return;
    }else{
     $("div[name=" + currentSubNav + "]").animate({"left": "+=600px", "opacity": "toggle"}, "slow");
     $("div[name=" + newName + "]").css({"margin-top": "0"});
     $("div[name=" + newName + "]").fadeIn(2000);
     $("div[name=" + currentSubNav + "]").animate({"left": "-=600px"}, 0);
     currentSubNav = newName;
     return;
    }
});

I'm using Chrome at the moment, and according to the dev tools that isn't what happens.

Problem #1

"$(this).attr("id");" isn't returning undefined as the documentation claims. It seems to be returning "". BUT, when I have the if statement as I do above, it skips over the statement entirely. I set a breakpoint, but it never pauses execuation, so the statement is never evaluated.

Problem #2

After the animations occur, instead of using the return at the end of the statements it goes back and uses the return for the "newName == currentSubNav" if statement. I guess that not a big deal, but it's not the intended behavior.

I'm fairly new to JavaScript, and it appears I'm missing something about how JavaScript works. But I can't find what anywhere. Any help?

Blockquote

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery