0

How can I use several click events on the same element in JavaScript?

I try to make that when I click on the h3 element it opens its description and then I again click on the element it closes the description.

var p, img,  question;

    function clickOn(){
        img = document.getElementsByClassName('down-arrow')[0];
        p = document.querySelectorAll('p')[0];
        p.setAttribute('class','show-text');
        /*img.setAttribute('class','show');*/
    }

     function clickOff(){
        img = document.getElementsByClassName('down-arrow')[0];
        p = document.querySelectorAll('p')[0];
        p.removeAttribute('class','show-text');
        /*img.removeAttribute('class','show');*/
        } 


    question = document.getElementsByClassName('question')[0];

    question.addEventListener('click', clickOn, false);
    question.addEventListener('click', clickOff, false);
Danilo Ivanovic
  • 1,216
  • 1
  • 10
  • 18
  • I think it is easier to have a single listener and then a global variable that controls if is open or closed, to do the opening or to close... – Calvin Nunes Nov 26 '20 at 12:53
  • Does this answer your question? [adding multiple event listeners to one element](https://stackoverflow.com/questions/11845678/adding-multiple-event-listeners-to-one-element) – Danilo Ivanovic Nov 26 '20 at 12:58

2 Answers2

1

Try using toggle for adding and removing class https://www.w3schools.com/howto/howto_js_toggle_class.asp:

var p, img,  question;

function clickOn(){
    img = document.getElementsByClassName('down-arrow')[0];
    p = document.querySelectorAll('p')[0];
    p.classList.toggle('show-text');
}

question = document.getElementsByClassName('question')[0];

question.addEventListener('click', clickOn, false);
gubnich
  • 61
  • 2
0

You can declare a global variable

var isTextDisplayed = false;

Then you can call same event listener and open or close the description on basis of the bit. For example

document.getElementById("myBtn").addEventListener("click", function() {
  if(!isTextDisplayed) {
    //HIDE DESCRIPTION CODE
  }
  else {
    //SHOW DESCRIPTION CODE
  }
  isTextDisplayed = !isTextDisplayed;
});

Full code:

var isTextDisplayed = false;
var description = document.getElementById("description");
document.getElementById("myBtn").addEventListener("click", function() {
      if(!isTextDisplayed) {
        description.style.display = 'none';
      }
      else {
        description.style.display = 'block';
      }
      isTextDisplayed = !isTextDisplayed;
    });
<h3 id="myBtn">CLICK TO TOGGLE DESCRIPTION</h3>

<p id="description">
  Some dummy text for description goes here in the block
</p>

For demo, see JSFIDDLE CODE

Ahmad Habib
  • 2,053
  • 1
  • 13
  • 28