javascriptjqueryhashtag

Append #hashtag to link in HTML on the fly


I have a nav, each link in the nav just appends a hashtag on the existing URL when clicked, for live filtering, etc. with the use of jQuery.

I want to append the SAME current hashtag to a series of links within a div further down the page.

For example, I've clicked "work" and my URL now looks like:

http://www.domain.com/page.html#work

I have a series of links in the page:

<div id="links">
<ul>
  <li><a href="http://www.domain.com/link1">Link1</a></li>
  <li><a href="http://www.domain.com/link2">Link2</a></li>
  <li><a href="http://www.domain.com/link3">Link3</a></li>
  <li><a href="http://www.domain.com/link4">Link4</a></li>
</ul>
</div>

These links within the div#links need to be updated on the fly to append #work on all the URL's so that when clicked the hashtag is appended.

Is this possible? Does this make sense?


Solution

  • You should attach a click event handler for links in #nav and change links in #links accordingly. [See it in action]

    Javascript

    $("#nav a").click(function() {
      $("#links a").each(function() {
        this.href = this.href.split("#")[0] + "#" + window.location.hash;
      });
    });​
    

    HTML

    <div id="nav">  
      <a href="#work">work</a> - 
      <a href="#school">school</a>
    </div>