search

Home  >  Q&A  >  body text

The rewritten title is: How to trigger JavaScript code when anchor is clicked in footer tag?

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粉002546490P粉002546490452 days ago552

reply all(1)I'll reply

  • P粉980815259

    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>

    reply
    0
  • Cancelreply