skip to Main Content

How to add EventListener to href with id "logout"? I do not want to add all EventListener to add anchors at once.

<a href="#" class="sub-menu-link">
    <img src="images/profile.png">
    <p>Edit Profile</p>
    <span>></span>
</a>
<a href="#" class="sub-menu-link">
    <img src="images/setting.png">
     <p>Settings & Privacy</p>
     <span>></span>
</a>
<a href="#" class="sub-menu-link">
     <img src="images/help.png">
     <p>Help & Support</p>
     <span>></span>
 </a>
 <a href="#" class="sub-menu-link" id="logout">
      <img src="images/logout.png">
      <p>Logout</p>
      <span>></span>
 </a>

3

Answers


  1. You can add like so.

    <a href="#" id="logout">Click me</a>
    <script>
      // Get the anchor element by its ID
      var myLink = document.getElementById('logout');
      // Add a click event listener
      myLink.addEventListener('click', function(event) {
        // Your code here
        alert('Link clicked!');
        // Prevent the default behavior (in this case, following the link)
        event.preventDefault();
      });
    </script>
    
    Login or Signup to reply.
    • Select the element you want to add event;
    let myElement = document.querySelector('#logout');
    
    • Add event;
    myElement.addEventListener('click', function() => {
        alert('Link clicked!');
        //Since it' s an anchor, prevent the default behaviour 
        event.preventDefault();
    })
    
    Login or Signup to reply.
  2. To put in another way, if you want to add event listeners only to specific anchor tags without adding them all at once, then you can create a common ancestor element and do event-delegation.

    <div id="menuContainer">
      <a href="#" class="sub-menu-link">
        <img src="images/profile.png">
        <p>Edit Profile</p>
        <span>></span>
      </a>
      <a href="#" class="sub-menu-link">
        <img src="images/setting.png">
        <p>Settings & Privacy</p>
        <span>></span>
      </a>
      <a href="#" class="sub-menu-link">
        <img src="images/help.png">
        <p>Help & Support</p>
        <span>></span>
      </a>
      <a href="#" class="sub-menu-link" id="logout">
        <img src="images/logout.png">
        <p>Logout</p>
        <span>></span>
      </a>
    </div>
    
    let menuContainer = document.getElementById("menuContainer");
    
    menuContainer.addEventListener("click", function(event) {
        if (event.target && event.target.matches("a#logout") {
            event.preventDefault();
    
            console.log("Logout element clicked!");
        }
    });
    

    This way, you only need to attach one event listener which is to the common ancestor element, even if you add more anchor tags in the future.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search