1 year ago

#381693

test-img

user2277105

Multiple Event Listeners - How To Refactor Them as One Function?

I have a navigation menu with sub menus like so:

<ul>
<li class="sub-menu">
    <a class="sub-menu-work" href="#" aria-expanded="false">Work</a>
    <ul class="sub-menu-work-items" data-visible="false">
        <li>
            <a href="/work/example-1">Example 1</a>
        </li>
        <li>
            <a href="/work/example-2">Example 2</a>
        </li>
    </ul>
</li>
<li class="sub-menu">
    <a class="sub-menu-blog" href="#" aria-expanded="false">Blog</a>
    <ul class="sub-menu-blog-items" data-visible="false">
        <li>
            <a href="/work/example-1">Blog Page 1</a>
        </li>
        <li>
            <a href="/work/example-2">Blog Page 2</a>
        </li>
    </ul>
</li>

Now I can write a bit of JS to toggle the aria-expanded to 'true/false' and the data visible to 'true/false' like so:

const subMenuWork = document.querySelector('.sub-menu-work');
const subMenuWorkItems = document.querySelector('.sub-menu-work-items');
const subMenuBlog = document.querySelector('.sub-menu-blog');
const subMenuBlogItems = document.querySelector('.sub-menu-blog-items');

// Toggle work
subMenuWork.addEventListener('click', () => {
    subMenuWork.setAttribute('aria-expanded', subMenuWork.getAttribute('aria-expanded') == 'false' ? 'true' : 'false');
    subMenuWorkItems.setAttribute('data-visible', subMenuWorkItems.getAttribute('data-visible') == 'false' ? 'true' : 'false');
})

// Toggle blog
subMenuBlog.addEventListener('click', () => {
    subMenuBlog.setAttribute('aria-expanded', subMenuBlog.getAttribute('aria-expanded') == 'false' ? 'true' : 'false');
    subMenuBlogItems.setAttribute('data-visible', subMenuBlogItems.getAttribute('data-visible') == 'false' ? 'true' : 'false');
})

My question is how can I create just one event listener that will toggle the values when the appropriate link is clicked on.

I do apologise as I'm relatively new to JS and, although I can get this to work, I realise that it is much much better to refactor and make it more modular. I had no idea what to search for so came here as a last resort.

Thanks in advance

javascript

html

navigation

dom-events

0 Answers

Your Answer

Accepted video resources