This is my footer HTML code:
<footer> <div> <a href='a.aspx'>test 1</a> <a href='b.aspx'>test 2</a> </div> <a href='c.aspx'>test 3</a> <footer>
Is there a way to always run a JavaScript function before a link redirect in ? And is it possible to find within the function where it will redirect to?
P粉9808152592023-09-08 11:32:28
Sure. .querySelectorAll
is the perfect selector for this.
var footerAnchors = document.querySelectorAll("footer a"); footerAnchors.forEach(anchor => addClickListener(anchor)); function addClickListener(anchor){ anchor.addEventListener('click', (event) => { alert(event.target.href); event.preventDefault() }) }
<footer> <div> <a href='a.aspx'>test 1</a> <a href='b.aspx'>test 2</a> </div> <a href='c.aspx'>test 3</a> <footer>