Where to add preventDefault() in this code block?

Advertisements

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?

>Solution :

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

Leave a Reply Cancel reply