user115422
user115422

Reputation: 4710

Detect change in hash value of URL using JavaScript

I'm working on a simple application which is single page based (due to project restrictions) and has dynamic content. I understand the dynamic content alright but what I don't understand is how to set-up a script that changes the html of a div when the hash value in the URL changes.

I need a JavaScript script to work as such:

Url: http://foo.com/foo.html div contents: <h1>Hello World</h1>

Url: http://foo.com/foo.html#foo div contents: <h1>Foo</h1>

How would this work?

Please help! Thanks.

Upvotes: 32

Views: 48598

Answers (3)

Rafiq
Rafiq

Reputation: 11455

Suppose we have list of items, each items has a hash tag as #id

const markup = `
        <li>
            <a class="results__link" href="#${recipe.recipe_id}">
                <figure class="results__fig">
                    <img src="${recipe.image_url}" alt="${limitRecipeTitle(recipe.title)}">
                </figure>
                <div class="results__data">
                    <h4 class="results__name">${recipe.title}</h4>
                    <p class="results__author">${recipe.publisher}</p>
                </div>
            </a>
        </li>
    `;

Now when a user click on any of those list item or reload (http://localhost:8080/#47746) an item with hash tag, hash event will be fired. To recive the fired hash event we must register hash event listener in our app.js

//jquery: 
['hashchange', 'load'].forEach(event => $(window).on(event, controlRecipe));
//js:
['hashchange', 'load'].forEach(event => window.addEventListener(event, controlRecipe));

catch the id in your controlRecipe function

const controlRecipe = async ()=>{
//jq
  const id =  $(window)..location.hash.replace('#','');
//js
  const id = window.location.hash.replace('#','');
  if(id){
    //console.log(id);
    state.recipe = new Recipe(id);
    try {
      await state.recipe.getRecipe();
      state.recipe.calcTime();
      state.recipe.calcServings();
      console.log(state.recipe);
    } catch (error) {
      alert(error);
    }
  }
}

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101604

personally, I'd use sammy which gives you the flexibility to template the hashtag (add placeholders and be able to read them back). e.g.

<script src="/path/to/jquery.js"></script>
<script src="/path/to/sammy.js"></script>
<script>
  $(function(){
      // Use sammy to detect hash changes
      $.sammy(function(){
          // bind to #:page where :page can be some value
          // we're expecting and can be retrieved with this.params
          this.get('#:page',function(){
              // load some page using ajax in to an simple container
              $('#container').load('/partial/'+this.params['page']+'.html');
          });
      }).run();
  });
</script>

<a href="#foo">Load foo.html</a>
<a href="#bar">Load bar.html</a>

An example can be found here: http://jsfiddle.net/KZknm/1/

Upvotes: 5

Ram
Ram

Reputation: 144689

You can listen to the hashchange event:

$(window).on('hashchange',function(){ 
    $('h1').text(location.hash.slice(1));
});

Upvotes: 77

Related Questions