Using window.location.hash in jQuery
Asked Answered
D

4

5

I would like to make a color fading navigation menu using jQuery, in which the "pressed" button corresponding to the current page behaves differently from the "unpressed" button (specifically, it doesn't fade to a different color upon hovering). If I look at the example at www.guitaracademy.nl, I see that they use native javascript with the window.location.hash property.

However, I can't seem to get this hash into jQuery. Here is an example script:

<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
    var p=window.location.hash;
    $("#clickme").click(function(){
        alert(p)
    });
});
</script>
</head>
<body>
<a href="#test">Click me first</a>
<div id="clickme">Then click me</div>
</body>
</html>

After loading this page, I click the "Click me first" link; then in the address bar I see "#test" appended to the original URL. However, if I then click the "Then click me" div I see an empty alert. It seems like the hash is not 'updating'.

I would greatly appreciate any help on this.

Desdee answered 24/10, 2011 at 19:14 Comment(0)
Z
6

Try moving the call for the hash to inside the function so that it gets called each time the click is called. The way you had it, it was only loading on the initial load of the page.

$(function(){
    $("#clickme").click(function(){
        var p=window.location.hash;
        alert(p)
    });
});
Zared answered 24/10, 2011 at 19:18 Comment(1)
Hi, yes that worked, thank you all for your (convergent) replies!Desdee
T
2

Try putting var p=window.location.hash; inside your click-listener:

<script type="text/javascript">
    $(function(){
        $("#clickme").click(function(){
            var p=window.location.hash;
            alert(p)
        });
    });
</script>
Thomas answered 24/10, 2011 at 19:20 Comment(0)
E
0

Your function for the #clickme div never attempts to update the hash. If you were expecting your code to update the hash you'll have to manipulate it like:

$("#clickme").click(function(){
    window.location.hash='#secondclick';

    //Remaining Code
});
Erida answered 24/10, 2011 at 19:19 Comment(0)
H
0

The hash is getting upadated but in this case the variable 'p' is not getting updated.

Here the assignment statement

var p=window.location.hash;

is executed only once when the page is loaded. So at the time of loading the value of P is empty, and always it will be empty.

Instead of

alert(p)

try

alert(window.location.hash)

or move the assignment inside the click callback. i.e just above alert statement

Holbein answered 24/10, 2011 at 19:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.