skip to Main Content

The goal here is to completely get rid of onclick in HTML and execute the function in JS instead through EventListener

Here is the short code below:

HTML

<button id="Toggle" onClick="MovelistShowHide('movelist')">Toggle Movelist On/Off</button>
    <div id="movelist">
        Movelist content
    </div>

CSS

 #movelist{display:none; background-color: lime;}

JS

function MovelistShowHide(element) {
  var srcElement = document.getElementById(element);
  if (srcElement != null) {
    if (srcElement.style.display == "block") {
      srcElement.style.display = 'none';
    }
    else {
      srcElement.style.display = 'block';
    }
    return false;
  }
}

3

Answers


  1. Chosen as BEST ANSWER

    ANSWER

    const btn = document.getElementById('Toggle');
    
    btn.addEventListener('click', () => {
      const move = document.getElementById('movelist');
    
      if (move.style.display === 'block') {
        move.style.display = 'none';
      } else {
        move.style.display = 'block';
      }
    });
    

  2. look at code

    <button id="Toggle" >Toggle Movelist On/Off</button>
      <div id="movelist">
         Movelist content
       </div>
    
    
    const btn = document.getElementById('Toggle');
     btn.addEventListener('click',function (e){
      var srcElement = document.getElementById("movelist");
        if (srcElement != null) {
         if (srcElement.style.display == "block") {
          srcElement.style.display = 'none';
          }
          else {
          srcElement.style.display = 'block';
         }
         return false;
        }
      } );
    
    Login or Signup to reply.
  3. Since we don’t know how many buttons/text divs you might end up having, and you’re already using CSS, I would suggest switching to classes – one to define the style of the text div(s), and another one that defines display: block called "show".

    When the button is clicked you can use the classList on the button’s nextElementSibling (ie the text div) to toggle the "show" class on and off.

    // Cache the buttons
    const buttons = document.querySelectorAll('button');
    
    // Add listeners to all of the them
    buttons.forEach(button => {
      button.addEventListener('click', toggleText);
    });
    
    // When a button is clicked toggle "show" class
    // using the classList on the button's next element
    // sibling (which is the text div)
    function toggleText() {
      this.nextElementSibling.classList.toggle('show');
    }
    .text { display: none; background-color: lime; padding: 0.25rem; margin: 0.25rem 0;}
    .show { display: block; }
    <section>
      <button type="button">Toggle 1 text</button>
      <div class="text">Text 1 content</div>
    </section>
    
    <section>
      <button type="button">Toggle 2 text</button>
      <div class="text">Text 2 content</div>
    </section>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search