0

I am using anchors in my URL as a kind of variable for JavaScript, eg:

mysite.com/itempage.html#item75

This works when I click the link on any other page, but not on the actual page in question (itempage.html).

Instead of reloading the page, clicking the link simply changes the URL. Since the page does not reload, none of my JavaScript runs again.

Does anyone know a way to reload the page with the new url?

So far I have tried:

HTML

<div id="itemmenu">
  <a id="item75" href="#">Item 75</a>
  <a id="item11" href="#">Item 11</a>
</div>

JQUERY

$( "#itemmenu a" ).each(function(index) { 
    $(this).on("click", function(){
        var linkid = $(this).attr('id'); 
        var winloc = "mysite.com/itempage#" + linkid;
        window.location  = winloc;
    });
});
MeltingDog
  • 14,310
  • 43
  • 165
  • 295

2 Answers2

1

This is indeed the expected behavior: not reloading the page, and simply scrolling the page to the anchor. Also, "#..." part is purely happening on client-side, and browsers don't send this part of the URI to the server, so:

are considered the same URIs for the server.

If you need to reload the page, you may do something as:

<div id="itemmenu">
  <a id="item75" href="?item=75">Item 75</a>
  <a id="item11" href="?item=11">Item 11</a>
</div>

If you don't need to reload the page, but just to rerun JavaScript, associate required JavaScript functions with the click event on any of the concerned links.


Additional notes:

  1. $(this).on("click", ...) can be shortened as $(this).click(...).

  2. You don't need your actual JavaScript code: set hrefs directly in HTML code instead of changing them through JavaScript.

Arseni Mourzenko
  • 50,338
  • 35
  • 112
  • 199
0

You could actually trigger a page reload with window.location.reload(), but I would advise against it.

Instead trigger all necessary code required for your page rendering here.

i.e.

function setupPageLayout() {
  // TODO: add any code that's supposed to run on page switch
}

$(document).on('load', setupPageLayout);

$('#itemmenu a').each(function(index) { 
  $(this).on("click", function(){
    setupPageLayout();
  });
});

Links should look like:

<a href="#item34">item</a>
Kevin Sandow
  • 4,003
  • 1
  • 20
  • 33
  • Note that the JavaScript code from the question doesn't serve its purpose. By reproducing it in your answer, you're inviting the OP to keep a useless piece of code. – Arseni Mourzenko May 31 '14 at 01:01