Jump to content

Function Works... Once?


Costanza

Recommended Posts

Description of the code:I have a few divs which act as buttons via an onClick function called "displayOptions()". When one of the divs (a category) is clicked, it displays a set of images(displayed elsewhere on the page in a separate container). The global variable "currentCategory" is used to track the status of whether or not images are currently displaying. What I would like to achieve is this functionality:--If no images are currently displayed then display the new set of images when a div is clicked.--If any images ARE currently displaying then 1) if the category of the just clicked div is the current category already, then simply remove the current images 2) if the category of the new div is different (AKA clicked a different div while other images were still displaying) then remove the current images then display the new category's images instead. (Note: The "images" are actually divs with background images) My problem:When I load the page in a web browser (Chrome, Firefox, Safari on both PC and Mac) it initially seems to work. I click a category div and it displays the correct images. Then I click the same div again or any other div and it removes the images just like it should--except when I've clicked a new category while other images are still displaying, it doesn't display the new images. It just removes the old ones. And when I try to click any div (after one set of images has been removed once) none of the divs will work anymore. The full code from my javascript file:

var currentCategory = 'none';var currentOptions = new Array();   function displayOptions(itemClass){if (currentCategory == 'none'){displayOptionsArray(itemClass);}else{for (var i = 0; i <= currentOptions.length; i++){currentOptions[i].style.display = 'none';}currentOptions = [];if (newCategory == currentCategory){currentCategory = 'none';}else{displayOptionsArray(itemClass);}}}   function displayOptionsArray(newCategory){currentCategory = newCategory;currentOptions = document.getElementsByClassName(currentCategory);for (var i = 0; i <= currentOptions.length; i++){currentOptions[i].style.display = 'block';}}

Images are contained inside this div (from CSS file):

#currentOptionsContainer{margin-left: auto;margin-right: auto;width: 1064px;position: relative;}

Same container div, but here is the HTML (the div/buttons are inside "equipContainer"):

<div id="equipContainer">				<div id="stockContainer" class="equipItem"><div class="itemBG"></div><div id="stock" class="itemContent" onClick="displayOptions('stock');"></div></div>		<div id="receiverContainer" class="equipItem"><div class="itemBG"></div><div id="receiver" class="itemContent" onClick="displayOptions('receiver');"></div></div></div> <div id="currentOptionsContainer"> 		<!--******Stocks******-->		<div class="stock item"><div class="itemBG"></div><div id="IdZ_stock" class="itemContent"></div></div>				<!--******Receivers******-->		<div class="receiver item"><div class="itemBG"></div><div id="receiver_standard" class="itemContent"></div></div></div>

Thank you, any help is appreciated!

Link to comment
Share on other sites

I don't see anything obviously wrong, so the first thing is to check for Javascript errors. In Chrome you can open the developer tools with Ctrl-Shift-I, and keep an eye on the Console tab. Also, add some debugging statements so you can verify what is happening. You can use console.log to write info to the developer console. Verify things like the number of items that are found, the currrent and new categories, etc. currentOptions = document.getElementsByClassName(currentCategory);console.log('Got ' + currentOptions.length + ' ' + currentCategory + ' items'); That should print something like 'Got 3 stock items', so you can verify that it's working correctly. You can also simplify this function a little bit:

function displayOptions(itemClass){  if (currentCategory != 'none')  {    for (var i = 0; i <= currentOptions.length; i++)    {      currentOptions[i].style.display = 'none';    }    currentOptions = [];  }  if (itemClass == currentCategory)  {    currentCategory = 'none';  }  else  {    displayOptionsArray(itemClass);  }}

That just calls displayOptionsArray once instead of checking in different places. I take it back, I saw a problem. In your original code you used newCategory instead of itemClass in the displayOptions function. newCategory is only defined in the other function.

Link to comment
Share on other sites

Thank you, that's cleaner code which is always good! Unfortunately though, I tested it and it's still acting the same as before. I can't understand what is causing it to only work once. I just tested the code in Chrome, Firefox, and Safari on PC and the latter 2 on Mac as well. All of them run the code the exact same way. I'm going to run a bunch of test statements to try to figure out where the issue occurs, like you suggested. I'll post back here again with the results. By the way, is it necessary for me to clear out an array using currentOptions = []; before I assign it to something new? If I simply were to run this linecurrentOptions = document.getElementsByClassName(currentCategory);without resetting the array first, what would happen? Would it auto-reset first or would it simply append new items?

Link to comment
Share on other sites

it would just overwrite the current value of the variable.
Ok, cool thanks! So my reset statement isn't even necessary unless I needed the array to have nothing in it while currentCategory = 'none'. Taking that out for now unless I later decide I need it.
Link to comment
Share on other sites

justsomeguy, I opened the page with Chrome and the console gave me this info: Starting from when I first open the page, it shows this. When I click on "Stock" it gives me this error:Uncaught TypeError: Cannot read property 'style' of undefined (line 34)displayOptionsArray (line 34)displayOptions (line 22)(anonymous function) (line 24)onclick (line 25) Then when I click on the div category "Stock" It says: Uncaught TypeError: Cannot read property 'style' of undefined (line 12)displayOptions (line 12)(anonymous function) (line 24)onClick (line 25) When I click on the div category "Receiver" It says: Uncaught TypeError: Cannot read property 'style' of undefined (line 12)displayOptions (line 12)(anonymous function) (line 25)onClick (line 26) I looked up the error lines in their respective files (I have 1 javascript file and 1 html file) and here they are:Line 12:

currentOptions[i].style.display = 'none';

Line 34:

currentOptions[i].style.display = 'block';

Line 22:

displayOptionsArray(itemClass);

Lines 24, 25, 26:

<div id="stockContainer" class="equipItem"><div class="itemBG"></div><div id="stock" class="itemContent" onClick="displayOptions('stock');"></div></div><div id="receiverContainer" class="equipItem"><div class="itemBG"></div><div id="receiver" class="itemContent" onClick="displayOptions('receiver');"></div></div><div id="triggerGroupContainer" class="equipItem"><div class="itemBG"></div><div id="triggerGroup" class="itemContent"></div></div>

I also ran your console test. Before clicking any buttons, it said:

got 0 itemsundefined

After clicking either button once, it shows correctly the number of items and the current category (but it still said u"undefined" underneath). But after clicking either button again, it still gave the same response which i guess means that it's simply resolving the function after un-displaying all the divs instead of doing what it's supposed to which is to go onto the next "if statement".

Link to comment
Share on other sites

so those variables are undefined. Have you looked at those lines to see what those variables are? Can you see why they would be undefined? Sounds like a bad element reference. can you post the entire code as it is now, or do you have a live example of your latest code?

Link to comment
Share on other sites

so those variables are undefined. Have you looked at those lines to see what those variables are? Can you see why they would be undefined? Sounds like a bad element reference. can you post the entire code as it is now, or do you have a live example of your latest code?
Here is my entire Javascript file:
var currentCategory = 'none';var currentOptions = new Array();   function displayOptions(itemClass){  if (currentCategory != 'none')  {	for (var i = 0; i <= currentOptions.length; i++)	{	  currentOptions[i].style.display = 'none';	}  }  if (itemClass == currentCategory)  {	currentCategory = 'none';  }  else  {	displayOptionsArray(itemClass);  }}   function displayOptionsArray(newCategory){currentCategory = newCategory;currentOptions = document.getElementsByClassName(currentCategory);for (var i = 0; i <= currentOptions.length; i++){currentOptions[i].style.display = 'block';}}

This is what is everything inside my html file's body tag:

<div id="masterContainer"><div id="equipContainer">				<div id="stockContainer" class="equipItem"><div class="itemBG"></div><div id="stock" class="itemContent" onClick="displayOptions('stock');"></div></div>		<div id="receiverContainer" class="equipItem"><div class="itemBG"></div><div id="receiver" class="itemContent" onClick="displayOptions('receiver');"></div></div>		<div id="triggerGroupContainer" class="equipItem"><div class="itemBG"></div><div id="triggerGroup" class="itemContent"></div></div>			</div>		<div id="currentOptionsContainer">	 <!--******Stocks******-->	 <div class="stock item"><div class="itemBG"></div><div id="skeleton_short" class="itemContent"></div></div>		<div class="stock item"><div class="itemBG"></div><div id="skeleton_long" class="itemContent"></div></div>		<div class="stock item"><div class="itemBG"></div><div id="skeleton_long_cheekrest" class="itemContent"></div></div>		<div class="stock item"><div class="itemBG"></div><div id="KV_standard" class="itemContent"></div></div>		<div class="stock item"><div class="itemBG"></div><div id="KV_cheekrest" class="itemContent"></div></div>		<div class="stock item"><div class="itemBG"></div><div id="KV_cheekrest_MARS" class="itemContent"></div></div>		<div class="stock item"><div class="itemBG"></div><div id="IdZ_stock" class="itemContent"></div></div>				<!--******Receivers******-->	 <div class="receiver item"><div class="itemBG"></div><div id="receiver_standard" class="itemContent"></div></div>	</div></div>

As for it saying that currentOptions is undefined, I can't understand that. Because as you can see, it clearly is defined when I assign it the new value of getElementsByClassName(currentCategory). And we know the assignment works because the FIRST time I click one of the buttons, it does indeed work and display all the correct items. I keep reading over my entire code over and over, following the various potential paths that the inputs would follow, but I can't find any problem (that I'm aware of. I'm not a Javascript expert so I could easily overlook something) Thank you guys for your time and trying to help me out. It's all appreciated. I'm doing this as a fun creative project to share with friends and a gaming community site, but these confusing errors are like brick walls.

Link to comment
Share on other sites

I fixed it! Oh man, this is really embarrassing. The problem was that it wasn't exiting the "for" loop because I had made the loop try to run 1 too many times (due to me having written <= instead of just <) Thanks for your help guys! Without your help i wouldn't have cleaned up the code better or have known to use Chrome's console to figure out the error which lead to me to solution.

Link to comment
Share on other sites

how about the CSS? The HTML doesn't really display much for me when trying to test locally. nm. glad you found it! :)

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...