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.
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>
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'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With