Home > front end >  Where to add preventDefault() in this code block?
Where to add preventDefault() in this code block?

Time:11-17

In this code I am trying to figure out where to add preventDefault()

document.addEventListener("DOMContentLoaded", function(event) {
    var element = document.querySelectorAll('li.nav-item');
    if (element) {
        element.forEach(function(el, key){
            el.addEventListener('click', function () {
                el.classList.toggle("active");
                element.forEach(function(ell, els){
                    if(key !== els) {
                        ell.classList.remove('active');
                    }
                });
            });
        });
    }
});

The problem is I have tried element.preventDefault(), with el. and even ell. but no look.

This is the corresponding html

<ul class="navbar-nav text-center">
    <li class="nav-item active">
        <a class="nav-link" aria-current="page" href="#">a</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#">a</a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="#">a</a>
    </li>
</ul>

Is the problem that I am tagetting the 'li' and not the 'a' within the 'li' itself?

CodePudding user response:

Use an event parameter where your click event triggers. And, use preventDefault there instead since you want to stop clicking event.

document.addEventListener("DOMContentLoaded", function() {
    var element = document.querySelectorAll('li.nav-item');
    if (element) {
        element.forEach(function(el, key){
            el.addEventListener('click', function (event) {
                event.preventDefault();
                el.classList.toggle("active");
                element.forEach(function(ell, els){
                    if(key !== els) {
                        ell.classList.remove('active');
                    }
                });
            });
        });
    }
});

CodePudding user response:

preventDefault is a property of the event, not of the element itself. Not sure about your exact use case, but you can try something like the below.

(I.e. add a parameter to the onclick handler, called e, and call e.preventDefault();)

el.addEventListener('click', function (e) {
  e.preventDefault(); // <-- here

  el.classList.toggle("active");
  element.forEach(function(ell, els){
      if(key !== els) {
          ell.classList.remove('active');
      }
  });
});
  • Related