Onclick Javascript Function Working Only On Second Click
Solution 1:
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
.
functiontoggleDivFunction () {
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)";
}
}
<pclass="dropdownHeader">TOP <spanid="arrowRight"class="arrowRight"onclick="toggleDivFunction();"> > </span></p><divclass="dropdownText"id="dropdownText"><p>TEXT TO BE SHOWN</p></div>
Solution 2:
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'
.
Solution 3:
You want to assign your event handlers earlier:
window.onload=toggleDivFunction;
and remove the onclick='toggleDivFunction()', its unneccessary then and oldfashioned.
Your code assigns a listener when an event is triggered (toggleDivFunction). To trigger the listener (arrowElement.onclick) you need to cause another event doing a second click.
Solution 4:
remove the arrowElement.onclick = function() {}
Why?
you have already apply the function in
onclick=toggleDivFunction()
witharrowRight
.so first execute thetoggleDivFunction()
then to perform theDom
arrowElement.onclick
.use any one of the onclick function ,not both
functiontoggleDivFunction() {
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)";
}
}
<pclass="dropdownHeader">TOP <spanid="arrowRight"class="arrowRight"onclick="toggleDivFunction();"> > </span></p><divclass="dropdownText"id="dropdownText"><p>TEXT TO BE SHOWN</p></div>
Post a Comment for "Onclick Javascript Function Working Only On Second Click"