Jump to content

[SOLVED] Query: JS Variables


Recommended Posts

The code below works fine (apart from in Safari but that's a different problem). You can see the working code in action here: http://codepen.io/deldalton/full/mfoIi

function expandNav() {  var nav = document.getElementById("navBar");  if (nav.className == "collapsed") {    nav.className = "expanded";    document.getElementById("navButton").src="images/lightNavUp.png";}    else {      nav.className = "collapsed";      document.getElementById("navButton").src="images/lightNavDown.png";}}function changeIconOnMouseOver() {  if (document.getElementById("navBar").className == "collapsed") {    document.getElementById("navButton").src="images/lightNavDown.png";}    else {      document.getElementById("navButton").src="images/lightNavUp.png";}}function changeIconOnMouseOut() {  if (document.getElementById("navBar").className == "collapsed") {    document.getElementById("navButton").src="images/darkNavDown.png";}    else {      document.getElementById("navButton").src="images/darkNavUp.png";}}

However, using the following code which is basically the same thing except using global variables instead of "document.getElementById"s all the time, doesn't work.

var nav = document.getElementById("navBar");var button = document.getElementById("navButton");function expandNav() {  if (nav.className == "collapsed") {    nav.className = "expanded";    button.src="images/lightNavUp.png";}    else {      nav.className = "collapsed";      button.src="images/lightNavDown.png";}}function changeIconOnMouseOver() {  if (nav.className == "collapsed") {    button.src="images/lightNavDown.png";}    else {      button.src="images/lightNavUp.png";}}function changeIconOnMouseOut() {  if (nav.className == "collapsed") {    button.src="images/darkNavDown.png";}    else {      button.src="images/darkNavUp.png";}}

Can anyone tell me why?

Edited by deldalton
Link to post
Share on other sites

Because when you set the global variable, the elements you're trying to access haven't loaded yet.

 

Oh, I see.

 

I have two possible solutions. Can you please tell me if either of them are possible and/or whether there is a reason they would not be suitable?

 

1. Put the link to the script at the bottom of the HTML document so that all elements load first, then the script.

2. Put the global variables in the HTML document, then leave the link to the script in the <head> element, as usual.

Edited by deldalton
Link to post
Share on other sites

Those are both suitable methods. There's a third possibility: Create the variables first without a value and then set their values after an onload or a DOMContentLoaded event (getting that to work cross-browser is difficult, but jQuery has it done already with a document.ready() method or something similar)

  • Like 1
Link to post
Share on other sites

Those are both suitable methods. There's a third possibility: Create the variables first without a value and then set their values after an onload or a DOMContentLoaded event (getting that to work cross-browser is difficult, but jQuery has it done already with a document.ready() method or something similar)

 

I'd really like to try and put together something purely in JS, rather than having to use JQuery. I'll let you know how I get on.

 

Thanks, Ingolme!

Link to post
Share on other sites

Okay, so I added this to the top of my JS script.

var nav;var button;function updateVar() {	var nav = document.getElementById("navBar");	var button = document.getElementById("navButton");}

I then added this to my HTML.

<body onload="updateVar();">

It doesn't like that at all. But, I don't know why. Providing I've got the "onload" bit correct, then it'll call the updateVar function and update the global variables and we're away, surely?

Link to post
Share on other sites

could you be more specific? Are you looking in the error console? What does it say the problem is?

Link to post
Share on other sites

Hi TheScientist. My opening post shows two separate bits of JS code. The first batch works, and can be seen in action by following the CodePen link. The second batch, however, doesn't work.

 

Ingolme advised that it's because the script is loaded before the elements, that the variables are trying to identify, have been loaded. That makes sense. Ingolme then suggested that I could create some undefined variables and then use an onload function to provide the global variables with values. That makes sense, too.

 

So, I add the above onload code into my JS and HTML. Unfortunately, I'm still getting the same problem where it believes the global variables have not been defined.

 

I hope that helps clarify my question.

Link to post
Share on other sites

I asked you a question though. Look in your error console. You're not exactly telling us what is happening. Errors would extremely specific.

 

This would confirm that indeed the variables are undefined, because the issue, in updateVar, is that you are putting var before your variables. This will make these variables scoped locally to the updateVar function.

 

Remove the var, and the function will use the global variables.

  • Like 1
Link to post
Share on other sites

Sorry, TheScientist. If I'm honest, I don't even know how to get to an error console ...

 

But, I've turned error reporting on it IE and I get this first error when I hover over the icon, in the top right corner of the web page. I hope this helps.

 

Webpage error details

User Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E; MATM)Timestamp: Thu, 18 Jul 2013 14:12:00 UTC

Message: Unable to get property 'className' of undefined or null referenceLine: 21Char: 3Code: 0URI: file:../js/code.js

 

 

Which states "Unable to get property 'className' of undefined or null". And, in the JS there is code trying to get nav.className. "nav" is one of the variables.

 

I've read your last comment though and I see what you're saying. I'm basically trying to create a new variable when what I should be doing it just calling the global variable already created and changing its value.

 

 

EDIT: Which, by the way, I've just tried and now works. Thank you very much.

Edited by deldalton
Link to post
Share on other sites

Okay, so I added this to the top of my JS script.

var nav;var button;function updateVar() {	var nav = document.getElementById("navBar");	var button = document.getElementById("navButton");}

I then added this to my HTML.

<body onload="updateVar();">

It doesn't like that at all. But, I don't know why. Providing I've got the "onload" bit correct, then it'll call the updateVar function and update the global variables and we're away, surely?

The reason your code didn't work was because you were using the var keyword forcing the variables to be local to the updateVar function.

  • Like 1
Link to post
Share on other sites

For what it's worth, I would recommend avoiding global variables. Using document.getElementById to get a reference to an element is very fast in modern browsers, and then you don't have to worry about potential global naming conflicts.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...