I\'m writing a basic show/hide function that displays a block of content and changes some text from \"Show More Benefits\" to \"Show Less Benefits\" (and vice versa).
Fo
The reason you need to click twice:
element.style.display
refers to inline styles only.
Initially, your elements do not have a style
-attribute. As a result, element.style.display
returns the empty String:
function showHide(c,t) {
var c = document.getElementById("content");
var t = document.getElementById("text");
console.log("c.style.display is:" + c.style.display);
if (c.style.display === "none") {
c.style.display = "block";
t.innerHTML = 'See Less Benefits';
} else {
t.innerHTML = 'See More Benefits';
c.style.display = "none";
}
}
<div class="content" id="content"><br>
<p><span class="benefit-stat">$2B</span> lorem</p>
<p><span class="benefit-stat">$2B</span> ipsum</p>
<p><span class="benefit-stat">$100</span> ipsum</p>
<p><span class="benefit-stat">32%</span> ipsum</p>
</div>
<p class="benefits-drop" id="text" onclick="showHide()">See More Benefits</p>
Bad but simple solution:
Add the style="display: block"
to your initial HTML:
function showHide(c,t) {
var c = document.getElementById("content");
var t = document.getElementById("text");
console.log("c.style.display is:" + c.style.display);
if (c.style.display === "none") {
c.style.display = "block";
t.innerHTML = 'See Less Benefits';
} else {
t.innerHTML = 'See More Benefits';
c.style.display = "none";
}
}
<div class="content" id="content" style="display: none"><br>
<p><span class="benefit-stat">$2B</span> lorem</p>
<p><span class="benefit-stat">$2B</span> ipsum</p>
<p><span class="benefit-stat">$100</span> ipsum</p>
<p><span class="benefit-stat">32%</span> ipsum</p>
</div>
<p class="benefits-drop" id="text" onclick="showHide()">See More Benefits</p>
Better solution:
Instead of toggling style.display
between none
and block
, instead toggle the universal attribute hidden
:
function showHide() {
const c = document.getElementById("content");
const t = document.getElementById("text");
t.textContent = c.hidden ? 'See Less Benefits' : 'See More Benefits';
c.hidden = !c.hidden;
}
<div class="content" id="content" hidden><br>
<p><span class="benefit-stat">$2B</span> lorem</p>
<p><span class="benefit-stat">$2B</span> ipsum</p>
<p><span class="benefit-stat">$100</span> ipsum</p>
<p><span class="benefit-stat">32%</span> ipsum</p>
</div>
<p class="benefits-drop" id="text" onclick="showHide()">See More Benefits</p>
Another option, with transition animation:
<button class="Show">Show</button>
<button class="Hide">Hide</button>
<div id="target"></div>
<style>
.Hide{display:none;}
</style>
<script>
$('.Show').click(function() {
$('#target').show(500);
$('.Show').hide(0);
$('.Hide').show(0);
});
$('.Hide').click(function() {
$('#target').hide(500);
$('.Show').show(0);
$('.Hide').hide(0);
});
$('.toggle').click(function() {
$('#target').toggle('fast');
});
</script>