Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Onclick javascript function working only on second click

function toggleDivFunction() {
  var arrowElement = document.getElementById("arrowRight");
  var showElement = document.getElementById("dropdownText");
  arrowElement.onclick = function() {
    if (showElement.style.display == 'none') {
      showElement.style.display = 'block';
      document.getElementById("arrowRight").style = "transform: rotate(+90deg)";
    } else {
      showElement.style.display = 'none';
      document.getElementById("arrowRight").style = "transform: rotate(0deg)";
    }
  }
}
<p class="dropdownHeader">TOP <span id="arrowRight" class="arrowRight" onclick="toggleDivFunction();"> > </span></p>
<div class="dropdownText" id="dropdownText"><p>TEXT TO BE SHOWN</p></div>

The problem is that the dropdownText div only shows up after a second click on the arrowRight span. I have seen it as a common problem, but still failed in finding a solution. Any help would be appreciated.

like image 312
M. Vlad Avatar asked Feb 04 '23 14:02

M. Vlad


2 Answers

You do not need to bind a click event handler inside another click event handler. You have to use a single click event handler.

The show/hide functionality belongs to second click event handler and this is binded to your span DOM element after first click.

function toggleDivFunction () {
   var arrowElement = document.getElementById ("arrowRight");
   var showElement = document.getElementById ("dropdownText");
   if(showElement.style.display == 'none')
   {
      showElement.style.display = 'block'; 
      document.getElementById("arrowRight").style = "transform: rotate(+90deg)";
   }
   else
   {
      showElement.style.display = 'none';
      document.getElementById("arrowRight").style = "transform: rotate(0deg)";
   }
}
<p class="dropdownHeader">TOP <span id="arrowRight" class="arrowRight" onclick="toggleDivFunction();"> > </span></p>
<div class="dropdownText" id="dropdownText">
<p>TEXT TO BE SHOWN</p></div>
like image 177
Mihai Alexandru-Ionut Avatar answered Feb 07 '23 12:02

Mihai Alexandru-Ionut


Just adding to approved answer.

Check for showElement.style.display == ''.
Additionally, for switching to flex on first click itself, if you are using display = 'none' as default.

Example:

..
if (showElement.style.display == 'none' || showElement.style.display == '') {
..

if the style of text is display = 'none'.

like image 30
Safnas Avatar answered Feb 07 '23 11:02

Safnas