$2B lorem
$2B ipsum
$100 ipsum
32% ipsum
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";
}
}
$2B lorem
$2B ipsum
$100 ipsum
32% ipsum
See More Benefits
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";
}
}
See More Benefits
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;
}
$2B lorem
$2B ipsum
$100 ipsum
32% ipsum
See More Benefits