search

Home  >  Q&A  >  body text

Add the div's ID to the url after click and then remove it from the url after click close btn

I've done the part of adding the div's ID to the url, but after clicking the class speakers--overlay-close in this speaker--card I can't delete the button after I close it.

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've tested some split functions etc but it doesn't work and the url remains the same - using #id.

P粉676821490P粉676821490264 days ago489

reply all(2)I'll reply

  • P粉184747536

    P粉1847475362024-04-02 10:46:44

    I ended up doing something like this, but not sure if this is the right approach:

    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);
        }
    }

    reply
    0
  • P粉376738875

    P粉3767388752024-04-02 09:20:42

    Since the close button is inside the div, when you click it, the event propagates and runs the div's click event handler, which again adds the hash. You can stop event propagation by calling event.stopPropagation() in the close button event handler and then remove the hash from the 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 = '';
      });
    }
    

    reply
    0
  • Cancelreply