Reputation: 11
I have some text that I wish to display, or not, based on a test. I have placed the text in a <span /id="..."> block, and have found examples that show referencing the id directly (if...then below) or by using the document.getElementById function (...else below).
Both seem to work in my test case. I gather that using the getElementById function is correct. Is it also correct to reference without calling that function, or is this just a case where it works in this browser now, but may break using a different browser or browser version?
Is there a better method do accomplish this?
<span id="myText">Some text to display or hide</span>
<script type="text/javascript">
function SetVisibility()
{
if (button.checked)
{
myText.style.visibility="visible";
}
else
{
document.getElementById("myText").style.visibility="hidden";
}
}
Upvotes: 1
Views: 276
Reputation: 2800
According to this answer, it is a bad idea to use inline HTML event attributes.
You can also add an event listener by using getElementById
then adding addEventListener()
to your button
element like this:
document.getElementById("myButton").addEventListener("click", function() {
var myText = document.getElementById("myText");
myText.style.visibility = myText.style.visibility === "hidden" ? "visible" : "hidden";
})
<span id="myText">Some text to display or hide</span>
<button id="myButton">SetVisible</button>
It would be best to use eventListener()
to set up event handlers.
Upvotes: 1
Reputation: 1142
As mentioned in the comments, the support for this seems pretty widespread -- it started in IE and seems to work across Chrome/Firefox/Safari as of my testing just now. However, using global variables is often considered an anti-pattern outside of exceptional cases where it makes sense -- native web APIs or situations where you need to be able to access something globally, for example. Otherwise you run the risk of overwriting or being overwritten by other code trying to compete for those names. In short -- in this case, it is almost always better to use getElementById
, although it is good to be aware that this feature exists.
Upvotes: 0