I am trying two toggle to spans text, but it does not switch or bring back from display none to display block.
function tog() {
let fc = document.getElementById("fcol");
let fe = document.getElementById("ferr");
let pr = document.getElementById("pr");
cdisp = fc.style.display;
erdisp = fe.style.display;
if (erdisp !== "block") {
cdisp = "none";
erdisp = "block";
pr.innerHTML = fe.textContent;
} else {
erdisp = "none";
cdisp = "block";
pr.innerHTML = fc.textContent;
}
}
body {
text-align: center;
}
<span id = "fcol" style="display: block; font-size:24px; color: green;">Only letters please</span>
<span id="ferr" style="display: none; font-size:24px; color: red;">Only letters please 2</span>
<button onClick="tog()">Sub</button>
<div id="pr"></div>
3
Answers
You should create a class that you can toggle. This simplifies the logic greatly.
Just another way of speaking to this issue .. You are assigning the
string
of "block" and "none" to variablescdisp
anderdisp
. You are not assigning the entire DOM object, so you are simply changing the variable, not the state or style of the object. You still need to call on the DOM object itself.So rather than show you another way to do it, this should help you understand why your code didn’t work in the first place:
The issue you are facing in your code is that you are updating the values of the cdisp and erdisp variables but not reflecting these changes back to the styles of the respective elements.
You can update your code by assigning the updated values to the style.display properties of the respective elements. Here’s the updated code:
In this version, the if statement checks if the ferr element is hidden (none), and if so, it sets its display to block, and sets the fcol element to none. The text content is then updated in the pr element accordingly. The else statement does the opposite, setting fcol to block and ferr to none.