skip to Main Content

I have done part with adding div’s ID to the url but I have trouble with then deleting it after clicking close button inside this speaker--card div with class speakers--overlay-close.

    var myDivs = document.getElementsByClassName('speakers--card');
    var closeDiv = document.getElementsByClassName('speakers--overlay-close');

    for(var i = 0; i < myDivs.length; i++) {
        myDivs[i].addEventListener('click', function (event) {
          console.log(this.getAttribute("id"));
          let thisID = this.getAttribute("id");
          window.location.href = window.location.href + "#" + thisID;
        });
    }

I have tested some split functions etc. but it is not working and url stays the same – with the # + id.

2

Answers


  1. Chosen as BEST ANSWER

    I have done something like this finally but not sure if it is the right way:

    var myDivs = document.getElementsByClassName('speakers--card');
    var closeDivs = document.getElementsByClassName('speakers--overlay-close');
    
    for(var i = 0; i < myDivs.length; i++) {
        myDivs[i].addEventListener('click', function (event) {
          let thisID = this.getAttribute("id");
          window.location.href = window.location.href + "#" + thisID;
        });
    }
    for(var i = 0; i < closeDivs.length; i++) {
        var closeDiv = closeDivs[i];
        closeDiv.onclick = function() {
          var newURL = location.href.split("#")[0];
          window.history.pushState('object', document.title, newURL);
        }
    }
    

  2. Since the close button is inside the div, when you click on it the event propagates and runs the click event handler for div which again adds the hash value. You can stop the event propagation by calling event.stopPropagation() in close button event handler and then remove the hash from url.

    var myDivs = document.getElementsByClassName('speakers--card');
    var closeDiv = document.getElementsByClassName('speakers--overlay-close');
    
    for (var i = 0; i < myDivs.length; i++) {
      myDivs[i].addEventListener('click', function (event) {
        let thisID = this.getAttribute("id");
        window.location.hash = thisID;
      });
    
      closeDiv[i].addEventListener('click', function (event) {
        event.stopPropagation();
        window.location.hash = '';
      });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search