Search code examples
javascripthtmlzurb-foundationzurb-foundation-5

Foundation 5: call js function from topbar dropdown anchor


Maybe I am being stupid here but I cannot figure out how to respond to a Foundation 5 TopBar dropdown selection with a javascript function. I would like to select a theme for a library I use. To set the theme I need to call a js function.

What I have is:

<div class="fixed">
<nav class="top-bar" data-topbar role="navigation">
    <section class="top-bar-section">
        <!-- Right Nav Section -->
    <ul class="right">
        <li class="has-dropdown">
            <a href="#">Theme</a>
            <ul class="dropdown" id="theme-dropdown">
                <li><a href="#">Light</a></li>
                <li><a href="#">Dark</a></li>
            </ul>
        </li>
    </ul>
    </section>
</nav>
</div>

these are of course contained in the topbar <nav>, etc and the dropdown on the topbar works great in basic HTML mode.

What I am struggling with is how do I make the 2 <li><a> elements (light and dark themes) call my JavaScript function setTheme(themeName) when they are clicked?

I cannot seem to find any examples where someone wants to call js from a topbar rather than a URL.


Solution

  • It looks like you aren't using a JavaScript framework? If you are, you should investigate how that framework can help you handle events. Otherwise, here are some ideas:

    1. onclick attribute

    So long as your setTheme function is defined globally you can call it from within the onclick attribute of a list item.

    var span = document.querySelector('span');
    function setTheme (themeName) {
      span.innerText = themeName;
    }
    <li onclick="setTheme('light')">Light</li>
    <li onclick="setTheme('dark')">Dark</li>
    
    Selected theme: <span>none</span>

    2. addEventListener method

    If your function setTheme is not global, target the element using your preferred approach within scope of the function and attach an event handler to the 'click' event using addEventListener.

    var listElems = document.querySelectorAll('li');
    [].forEach.call(listElems, function (elem) {
      elem.addEventListener('click', function () {
        console.log("HI");
        setTheme(this.dataset.value);
      });
    });
    
    var span = document.querySelector('span');
    function setTheme (themeName) {
      span.innerText = themeName;
    }
    <li data-value="light">Light</li>
    <li data-value="dark">Dark</li>
    
    Selected theme: <span>none</span>