Skip to content
Advertisement

Dropdown on click doing nothing

I am just starting JS, so this may be a stupid question. I want to make a dropdown, where if you pick one option the related paragraph would be visible. I didn’t really know how to start this so I created the cars function to make the “e38value” paragraph visible when clicking the e38 button, but nothing happens when I click on it, and I have no clue why. If someone knows a better way doing this and it is not so complicated and a beginner could understand it I would be very happy if you could share it with me.

var e38 = document.querySelectorAll('e38value')

function cars() {
  document.querySelectorAll('e38').onclick = function() {
    console.log('clicked');
    e38.classList.toggle("e38hidden");
  }
}
.e38hidden {
  display: none;
}
<nav>
  <menu>
    <menuitem id="kocsid">
    <a>Amilyen kocsid van</a>
    <menu>
      <menuitem id="Audi">
      <a>Audi</a>
      <menu>
        <menuitem><a>Audi</a></menuitem>
        <menuitem><a>Audi</a></menuitem>
        <menuitem><a>Audi</a></menuitem>
        <menuitem><a>Audi</a></menuitem>
      </menu>
      </menuitem>
      <menuitem id="BMW">
      <a>BMW</a>
      <menu>
        <menuitem><a class="e38">750 e38</a></menuitem>
        <menuitem><a>760 e65</a></menuitem>
        <menuitem><a>M3 e46</a></menuitem>
        <menuitem><a>M3 e62</a></menuitem>
      </menu>
      </menuitem>
      <menuitem id="Dodge">
      <a>Dodge</a>
      <menu>
        <menuitem onclick=""><a>Dodge</a></menuitem>
        <menuitem><a>Dodge</a></menuitem>
        <menuitem><a>Dodge</a></menuitem>
        <menuitem><a>Dodge</a></menuitem>
      </menu>
      </menuitem>
</nav>
<p id="e38value" class="e38hidden">e38 value</p>

Advertisement

Answer

there are probably other better ways to acomplish that but here is how to fix you script:

function cars() {
  document.querySelectorAll('.e38').forEach(function(e) {
    e.onclick = function(evt) {
      console.log('clicked', evt.target.innerHTML);
      document.getElementById("e38value").classList.toggle("e38hidden");
    }
  })
}

cars();

Note:

  1. You need to call cars() to actually initialise the events.
  2. The selector should be “.e38” which means all elements with the e38 class
  3. You need to call forEach as the querySelector returns an array of elements (in that case with only one element)
  4. The click event can be used to locate the target (where it was clicked).

Here is a fiddle: https://jsfiddle.net/b9728Lmk/1/

Does that solve the problem?

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement