Why can’t I get this to work??
I want to get the index() from the menu, and alert() the value when the hash changes, which it does.
The alert doesn’t appear.
$('#menu li a').click(function() {
var index = $(this).parent().index()+1;
});
$(window).bind('hashchange', function () { //detect hash change
var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
alert(index);
});
Can you tell me what I’m doing wrong???
This is a scoping issue, the
indexvariable is local to the function it’s declared in, so you can’t access it from the other function. Move the declaration to the outer scope and it will work:I suggest reading up on how scoping works in JavaScript – JS Garden has a decent overview.