skip to Main Content

I have a select with options that have values that are populated with jQuery based on data attributes from divs.
When a user select an option, the div with the data attribute that matches the value of the option is displayed.
Now I’m trying to create a deep linking option, so when I have a url like https://my-site.com/page/#option-2 the option-2 is preselected in the select and the div with data attribute option-2 is displayed.
So far I have this javascript:

$(window).on('load', function() {
  let urlHash = window.location.hash.replace('#','');
  console.log(urlHash);

  if ( urlHash ) {
    $('.dropdown').val(urlHash);
    $('body').find('.location').removeClass('is-active');
    $('body').find(`.location[data-location-hash=${urlHash}]`).addClass('is-active');
  }
});

If I enter the url https://my-site.com/page/#option-2 the site goes in infinite loop and never loads without displaying any error in the console..
If I refresh the page while loading, the console.log is displayed with the correct string that I’m expecting, but the .location[data-location-hash=option-2] is not displayed and the option is not selected…
I’m using the same code for the change function of the dropdown and is working, but it’s not working in the load function.. Is there anything I’m missing?

JSFiddle, if it’s of any help:
https://jsfiddle.net/tsvetkokrastev/b0epz1mL/4/

2

Answers


  1. Chosen as BEST ANSWER

    Solved it by using a function instead of $(window).on('load').. Also added $( window ).on( 'hashchange', function( ) {}); to assure that the js will run again after the hash is changed. Here is an updated jsfiddle: https://jsfiddle.net/tsvetkokrastev/b0epz1mL/5/


  2. Your site is looping because you are doing a window.location.replace
    To get the urlHash you should use

    $(window).on('load', function() {
      var href = location.href; // get the url
      var split = href.split("#"); // split the string
      let urlHash = split[1]; // get the value after the hash
    
      if ( urlHash ) {
        $('.dropdown').val(urlHash);
        $('body').find('.location').removeClass('is-active');
        $('body').find('.location[data-location-hash='+urlHash+']').addClass('is-active');
      }
    });
    

    https://codepen.io/darkinfore/pen/MWXWEvM?editors=1111#europe

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search