Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Where to add preventDefault() in this code block?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading