Home > Back-end >  Javascript targeting the first element only with a double click issue
Javascript targeting the first element only with a double click issue

Time:06-17

I'm learning JavaScript at the moment (started 3 weeks ago at college) and i'm struggling to create a mobile menu whereby you click and that reveals or hides a hidden menu.

The issue here is that JS only targets the first class and not all of them. And you need to click twice to reveal the element that does work.

I would be very grateful for some guidance, and hopefully an expiation to help me understand the problem.

Thank you

<script>
const btn = document.querySelector('.navigation-main-mobile .menu-item-has-children');
const box = document.querySelector('.navigation-main-mobile .menu-item-has-children .sub-menu');

btn.addEventListener('click', function handleClick() {
if (box.style.display === 'none') {
    box.style.display = 'block';
} else {
    box.style.display = 'none';
}
});
</script>

<ul id="menu-primary-menu" ><li><a href="/">Text</a></li>
    <li ><a href="#">Text</a>
        <ul >
            <li><a href="http://1.io/1/1/">Text</a></li>
            <li><a href="http://1.io/2/2/">Text</a></li>
            <li><a href="http://1.io/3/3/">Text</a></li>
        </ul>
    </li>
    <li ><a href="/news/" aria-current="page"></a>Text</a></li>
    <li ><a href="#"></a>Text</a></li>
        <ul >
            <li><a href="http://1.io/4/">Text</a></li>
            <li><a href="http://1.io/5/">Text</a></li>
            <li><a href="http://1.io/6/">Text</a></li>
            <li><a href="/about/">Text</a></li>
        </ul>
    </li>
</ul>

CodePudding user response:

You have to find all nodes which match the selector. querySelectorAll is used for that. Then you must loop through all the nodes and set the event. Also, you have to remove the wrong closing <li> tag (which messes up the selector) after </a>Text</a> in the second menu-item-has-children

const btns = document.querySelectorAll('.navigation-main-mobile .menu-item-has-children');
const boxs = document.querySelectorAll('.navigation-main-mobile .menu-item-has-children .sub-menu');


btns.forEach((btn, index) => {
btn.addEventListener('click', function handleClick() {
if (boxs[index].style.display === 'none') {
    boxs[index].style.display = 'block';
} else {
    boxs[index].style.display = 'none';
}
})});

CodePudding user response:

  1. .querySelector() returns the first element that matches the values passed.

  2. You are getting the double click issue because you have not set a value for the style.display attribute. When you click it for the first time the browser realized that and set the attribute to none and then the second click performs the changes that you coded.

Remember to be somewhat explicit in what you want to code and do not assume that the computer is going to complete anything for you. Good Luck!

  • Related