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粉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); } }
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 = ''; }); }