G-Sun
G-Sun

Reputation: 3

Page reload on hash change with Javascript

I'm nearly there with my code, highligting div based on selected clicked a with hash id.

The only problem left is the page is not reloading on click

Here's the code:

<script type="text/javascript">
var idh = window.location.hash

   $(document).ready(function(){
     $("a"+idh).parents("div:first").addClass("uthevet");

     $(".Nytt-over a").click(function() {
       var newLoc = this.attr('id');
       window.location.hash = newLoc;
       location.reload();
    });
});
</script>

I see the hashtag changing on click, but no reload. What do I do wrong?

Page http://relasjonsledelse.no/Nytt/Nyheter.asp#BiGO (Click on one of the headings in the body, this should change the highlighted area)

Upvotes: 0

Views: 704

Answers (2)

Jegan
Jegan

Reputation: 595

Just use the below code

var newLoc = $(this).attr('id');

instead of

var newLoc = this.attr('id');

Surely it will work. When you give 'this' it doesn't call the jQuery function to get attribute id. And one more thing is no need to specify the the window object and again call reload, simply set like

location.hash = 'your link';

Upvotes: 1

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93611

You needed to wrap this in a jQuery object in the click handler. It was failing on the call to attr:

$(".Nytt-over a").click(function() {
       var newLoc = $(this).attr('id');
       window.location.hash = newLoc;
       location.reload();
    });

Or use var newLoc = this.id; as Joe suggests :)

When in doubt, use the F12 debugger consoles provide by Chrome, IE etc.

Upvotes: 3

Related Questions