Can't change variable in if/else - javascript

I can't find a reason why the following code is not working:
var nav = document.getElementById("nav").style.visibility;
if (nav === "" || nav === "hidden")
nav = "visible";
else
nav = "hidden";
Can someone explain me why I cannot change nav in the if..else?

Because you're only assigning a value to a variable rather than updating that element.
var nav = document.getElementById("nav");
var visibility = nav.style.visibility;
if (visibility === "" || visibility === "hidden")
nav.style.visibility = "visible";
else
nav.style.visibility = "hidden";

Consider this
if (visibility === "" || visibility === "hidden")
document.getElementById("nav").style.visibility = "visible";
else
document.getElementById("nav").style.visibility = "hidden";
First layout the logic in code, the way you want it to work. Seems really clear what this code is about. At least it should to yourself! Once that is done, you can factor out the things your code might need later in the program. For example, if you will change the visibility of the element some more, then you will need to extract it to the outer scope.
var element_style = document.getElementById("nav").style;
if (visibility === "" || visibility === "hidden")
element_style.visibility = "visible";
else
element_style.visibility = "hidden";
In there, you had to leave out the .visibility from the element_style because then (in your if block) you are accessing the property of the object via . operator and assignment = and assigned it to string value. Meaning that your nav is assigned to a new string with a value of "visible or hidden", and you totally detached the object you wanted to change (that nav element).
In your code, you can log the nav to see what are you getting to confirm.

Related

Trying to change display element through JS code: "Cannot read property 'style' of null"

I am a beginner with JS and I will usually find a good answer by googling, but unfortunately not this time. The code is supposed to start with the click of either one of two buttons. As you click the currentMenu integer goes either negative 1 or positive 1 depending on what button you press. Since there are only 4 menus to showcase if the currentMenu counter goes above 3 or under 0 the counter will reset.
var currentMenu = 0;
var menuEl0 = document.getElementById("team-member-ul");
var menuEl1 = document.getElementById("in-queue-ul");
var menuEl2 = document.getElementById("resolved-ul");
var menuEl3 = document.getElementById("in-progress-ul");
function testFunction(id) {
//Current selected object
if(id == "prev"){
currentMenu--;
alert("Left button was pressed");
}
if(id == "next"){
currentMenu++;
alert("Right button was pressed")
}
//Reset loop if int goes higher/lower than amount of menus
if(currentMenu < 0){
currentMenu = 3;
}
else if(currentMenu > 3){
currentMenu = 0;
}
alert(currentMenu);
enableDisableMenus();
}
function enableDisableMenus(){
//Enable/Disable menus
if(currentMenu == 0){
menuEl0.style.display = "inline-block";
menuEl1.style.display = "none";
menuEl2.style.display = "none";
menuEl3.style.display = "none";
}
if (currentMenu == 1){
menuEl0.style.display = "none";
menuEl1.style.display = "inline-block";
menuEl2.style.display = "none";
menuEl3.style.display = "none";
}
if (currentMenu == 2){
menuEl0.style.display = "none";
menuEl1.style.display = "none";
menuEl2.style.display = "inline-block";
menuEl3.style.display = "none";
}
if (currentMenu == 3){
menuEl0.style.display = "none";
menuEl1.style.display = "none";
menuEl2.style.display = "none";
menuEl3.style.display = "inline-block";
}
}
Is there anything particular wrong syntax in the code I am missing?
The error message clearly states Cannot read property 'style' of null means either or all of the four menuEl0 menuEl1 menuEl2 menuEl3 is null. It means when the line document.getElementById got executed there was no element in your DOM with such ID.
The reason can be that your JS got loaded first started executing, you can use defer in script load to prevent that. or the other thing is you can do is load the script after the body tag.
Whatever the case be you should always add a null check to avoid errors. Inside the function enableDisableMenus add check for all getElementById variables if it is null.

Close a Div element if you click outside of it

I need a function that hide the div if i click outside of the div area ?
I have defined a Div on Position: none, which I make visible by using the following function:
My Div:
<div id="TopBarBoxInfo1" onclick="showSerachOptions('BoxBox');" >
</div>
My function:
function showSerachOptions(element){
var element = document.getElementById(element);
// And then it will change what it is
if(element.id == 'Box'){
if(element.style.display == 'none'){
element.style.display = 'block';
}
else{
element.style.display = 'none';
}
}
}
Now I would need a function, which allows to close the div if you click with the mouse pointer outside of the area of the div. Please describe your solution in detail, because I am a beginner!
Since being registered doesn't mean knowing the rules i'm going to answer your question BUT you should always ask in english.
var body = document.getElementsByTagName('body')[0];
body.click = function(e){
//here you can get e.target as the click-target-element or
// e.srcElement(Microsoft) as the click-target-element
//than you can handle what you want to do since e.target/srcElement will give you
// an element (just like document.getElementById
}
remember the .click may not be the best way - addEventListener would be much better afaik

Div visibility toggle not working

I'm making a tree structure using html and css.
This is the final structure that I should reach: http://jsfiddle.net/yrE7N/1/
What I need is, on clicking a node, its children node will appear.
I've done this till now:
JS Fiddle: http://jsfiddle.net/ZTkLg/11/
I've used this JS function
var _hidediv = null;
function showdiv(id) {
if(_hidediv)
_hidediv();
var div = document.getElementById(id);
div.style.display = 'block';
_hidediv = function () { div.style.display = 'none'; };
}
The thing is, the JS function doesn't seem to be toggling the visibility of the div stage-two.
I've used this function before on this page: http://leonardorestaurant.in/menu and it worked but I can't figure the problem out in this case.
Try
Some text here
and
var flag = true;
function showdiv(id) {
var div = document.getElementById(id);
div.style.display = flag ? 'none' : 'block';
flag = !flag;
}
Demo: Fiddle
The console in my browser prints out :
Uncaught TypeError: Cannot read property 'style' of null
Which means that here :
div.style.display = 'block';
div is not the result you think it should be... That tells us that id is not what we think here :
var div = document.getElementById(id);
Which I confirmed by using :
console.log(id);
inside your function.
The id value is actually the <div id="two">
So, basically you already have the element you're looking for.
However, you've got bigger problems, which is that you need a toggle function, I'm just guessing. Try using this :
function toggleDiv(id) {
var el = document.getElementById(id);
var newDisplayValue = "none";
if ( el.style.display && el.style.display === "none" ) {
newDisplayValue = "block";
}
el.style.display = newDisplayValue;
}
and change to this :
<a href=# onclick="toggleDiv('two');">
see it here

Code explanation js

Wondering if someone can explain what this code means. What do the different lines mean and do?
function overlay(theTitle) {
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
el.innerHTML = theTitle;
}
function vindu(){
el=document.getElementById("vindu");
el.style.visibility=(el.style.visibility=="visible")?"hidden":"visible";
}
The only piece of this code that shouldn't be fairly self-explanatory is called the conditional operator (also called ternary).
For an example of how this works, val = test ? 'foo' : 'bar' is equivalent to the following:
if (test) {
val = 'foo';
} else {
val = 'bar';
}
el = document.getElementById("overlay");
searches an element in your html markup with the ID=overlay
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
sets the visibility style of the object to visible if it was hidden before and vice versa.
el.innerHTML = theTitle;
sets the innerHTML property to the variable which got passed in to the function. innerHTML is actually the content of the element and will show as text in your site
the other method does exactly the same for the element ID = vindu

div won't display on click of an image

No idea where the problem lies, tried various things and I'm not having any luck. I've done this successfully before in the past but now it won't work, any help would be great...
HTML snippet:
<tr>
<td class="tableContent noBorderSides paddingAll"><img class="imgResize" src="images/emptyCircle.png" onclick="expandItem()"/>
<div id="Expand" class="hiddenDiv">
HELLO?
</div>
JavaScript:
function expandItem() {
if (document.getElementById("Expand").style.display == 'block') {
document.getElementById("Expand").style.display = 'none';
}
else if (document.getElementById("Expand").style.display == 'none') {
document.getElementById("Expand").style.display = 'block';
}
}
CSS:
.hiddenDiv {
display: none;
}
What am I doing wrong?
The initial display that is set in your CSS won't be reachable from the .style property.
Do it like this:
function expandItem() {
var expand = document.getElementById("Expand");
if (expand.style.display == '') {
expand.style.display = 'block';
}
else if (expand.style.display == 'block') {
expand.style.display = '';
}
}
Or a little shorter like this:
function expandItem() {
var expand = document.getElementById("Expand");
expand.style.display = (expand.style.display == '') ? 'none' : '';
}
Use .getComputedStyle() to get any style attributes associated with a given element. Notice, that the object returned is read only, so you'll want to use this for the initial if statement, and then set the style as you were doing above.
You could just remove the class from the element that defines the hidden property and add when you want to hide:
if (document.getElementById("Expand").className == '') {
document.getElementById("Expand").className = 'hiddenDiv';
}
else if (document.getElementById("Expand").className == 'hiddenDiv') {
document.getElementById("Expand").className = '';
}
Do note that if you have other classes on that element you will need to do a little string manip rather than just a straight check and remove.
//Temporary solution
//Replace your javascript code with following code
if (document.getElementById("Expand").style.display == 'block') {
document.getElementById("Expand").style.display = 'none';
}
else{
document.getElementById("Expand").style.display = 'block';
}
//Note :- Javascript detect '' (empty) when it try to search display property for expand block
#user1689607's answer is right if you need to just use javascript. If you have access to jQuery you can do it like so
$("#Expand").toggle();
And a simple jsfiddle to demonstrate: http://jsfiddle.net/P36YA/

Categories