Toni Au Toni Au - 5 months ago 10
HTML Question

New to Javascript - changing style of element

So based on the value of a boolean, I want certain tabs in my sidebar to display/ hide when the page loads.



var someVar = true;

function show_ifTrue() {
if (Boolean(someVar) == true) {
document.getElementById('x').style.display = 'block';
console.log("I CHANGED IT");
}
else {
document.getElementById('x').style.background = 'red';
}
}

.sidebar {
position: fixed;
overflow-y: scroll;
top: 0;
bottom: 0;
float: left;
display: inline-block;
z-index: 50;
}
#tab {
display: block;
}
#x {
display: none;
}

<div class="sidebar">
<a href="#" id="tab"> Cats </a>
<a href="#" id="x" onpageshow="show_ifTrue();"> Dogs</a>
</div>





I have tried everything from taking out the display from
.sidebar a{...}
and giving each tab its own display property, using
!important
, changing in JS using
style.cssText
or setting attribute, I just can't get it to change the display.

Answer

In order to change the color, you have to call the function first, but you are never calling it, since onpageshow could only be added to <body>, so you could move it there - <body onpageshow='...'>. Or, if you still want to deal only with the div itself, do it onload:

window.onload=function(){
    show_ifTrue();
}

This way too could also use your pageshow:

window.onpageshow=function(){
    show_ifTrue();
}

Also, you don't need Boolean prefix in your function, just someVar == true.