Jump to content
jimfog

Cannot Test If Condition

Recommended Posts

I have elements in a page that are hidden(display:none) I want to test that with an if statement:

var y=document.getElementsByClassName("show_hide"); y;if(y.style.display=none) {alert("Hi")};

It is some tests i am making because i want to put the above code in a larger chunk of code later. So, the elements in the page that have display:none have a class of "show_hide"-as you can see above. The problem is that when running the code in firebug i get TypeError: document.y is undefined I have tried also accessing a specific element in the collection but the results are the same:

if(y[1].style.display=="hidden"){alert("Hi")}; 

Well, what do you think?

Edited by jimfog

Share this post


Link to post
Share on other sites

why are you putting document before the y variable?

document.y

Edited by thescientist

Share this post


Link to post
Share on other sites

If the lines of code you posted above were right next to each other like they are, y wouldn't be undefined. It sounds like you're declaring y as a local variable and trying to use it as a global variable.

Share this post


Link to post
Share on other sites
If the lines of code you posted above were right next to each other like they are, y wouldn't be undefined. It sounds like you're declaring y as a local variable and trying to use it as a global variable.
Then, how i should write the code?

Share this post


Link to post
Share on other sites
why are you putting document before the y variable?
document.y

I corrected it. Still though, the code does not work.

Share this post


Link to post
Share on other sites

If you want to make a comparison, you have to use == and not =. You can't access y directly, you have to go to each node in the nodelist.

Share this post


Link to post
Share on other sites
If you want to make a comparison, you have to use == and not =. You can't access y directly, you have to go to each node in the nodelist.
I am little confused now, How i would go about writing the code?

Share this post


Link to post
Share on other sites
Then, how i should write the code?
Well, if you need to use y as a global variable, then declare it as a global variable. You might also want to pick a name other than "y" that isn't as likely to get used by something else. You can define it as window.y (or whatever name you want) if you want it to be global. Also, like Ingolme mentioned, the return of document.getElementsByClassName is not a single node, it's a list of them. You have to loop through it and test each one.

Share this post


Link to post
Share on other sites
I am little confused now, How i would go about writing the code?
Go to the XML DOM tutorial at W3Schools and look at node lists.

Share this post


Link to post
Share on other sites
Go to the XML DOM tutorial at W3Schools and look at node lists.
Very useful tutorial. I was searching something like this in the site(w3schools) and could not find such. I will rethink my code strategy and get back to mention what i have accomplished.

Share this post


Link to post
Share on other sites

Basically you are trying to do this

var y = document.getElementsByClassName('show_hide');if(y[0].style.display == 'none') { alert('Hi); }

That if statement will never return true. The style attribute of the element is not related to the CSS class. Trying to retrieve the css style property via javascript will only work when that style property has previously been set via javascript OR when that style property was defined inline by using the style attribute in (X)HTML.

Share this post


Link to post
Share on other sites

It depends when you want this alert to show, if you wish it to show as the class show_hide changes then you could use jquery to show the alert of hi, its current display value, or even retrieve info about elements that relate to that specific element.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Untitled Document</title><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script><script type="text/javascript">/*<![CDATA[*//*---->*/$(document).ready(function(){$(".testMenuItem1").click(function (){checkdisplay($(this).next("form").children("div.show_hide"))$(this).next("form").children("div.show_hide").slideToggle("slow");});});function checkdisplay(elem){if(elem.css("display")=="none"){alert("Hi")alert(elem.css("display"))alert(elem.parent("form").attr("id"))alert(elem.parent("form").prev(".testMenuItem1").attr("title"))}}/*--*//*]]>*/</script><style type="text/css"></style></head><body><a name="1" title="element1" class="testMenuItem1" id="id1" style="display:block;">08:00</a><form action="Proccess.php" method="post" id="form1"><div class="show_hide"><table border="0"><tr><td >Name</td><td><input type="text" name="name" maxlength="45" size="35" /></td></tr><tr><td>Phone</td><td><input type="text" name="phone" maxlength="45" size="35" /></td></tr><tr class="time"><td>Time</td><td><input type="text" name="time" maxlength="45" size="35" /></td></tr><tr><td><input class="submit" type="submit" value="submit" maxlength="25" size="15" /></td></tr></table></div></form><a name="1" title="element2" class="testMenuItem1" id="id2" style="display:block;">09:00</a><form action="Proccess.php" method="post" id="form2"><div class="show_hide"><table border="0"><tr><td>Name</td><td><input type="text" name="name" maxlength="45" size="35" /></td></tr><tr><td>Phone</td><td><input type="text" name="phone" maxlength="45" size="35" /></td></tr><tr class="time"><td>Time</td><td><input type="text" name="time" maxlength="45" size="35" /></td></tr><tr><td><input class="submit" type="submit" value="submit" maxlength="25" size="15" /></td></tr></table></div></form></body></html>

Edited by dsonesuk

Share this post


Link to post
Share on other sites

Sorry for the late reply. Let's go one by one. Aspnetguy, I set "display:none;" inline and now the code works. dsonesuk, Let me explain precisely what i want to accomplish.It was not my intention to mention it in this post but things came in a way i should it. As you see i have many clickable elements(testMenuItem1). Upon clicking the div class="show_hide" appears using the slidetoggle jQuery effect. Here is the logic: If ONE div class="show_hide" is ALREADY open, when the user goes to open a second div class="show_hide"(by clicking the corresponding element ), i want the first one to close and then the second to open. I do not want 2 div class="show_hide" open at the same time. Probably i will have to use a for loop to test each item separately. This loop must come to "play"(i assume) after the element is clicked(testMenuItem1).So, it must be contained in that function, in dsonesuk's code it must go somewhere here:

$(document).ready(function(){$(".testMenuItem1").click(function (){checkdisplay($(this).next("form").children("div.show_hide"))$(this).next("form").children("div.show_hide").slideToggle("slow");});

I have nothing more to add.Sorry for all this, i needed though to describe the problem as precisely as possible.

Share this post


Link to post
Share on other sites

Thats easy just hide, or slideup all div.show_hide before the toggle runs

$(document).ready(function(){$("div.show_hide").hide();$(".testMenuItem1").click(function (){$("div.show_hide").slideUp("medium");//$("div.show_hide").hide();$(this).next("form").children("div.show_hide").slideToggle("slow"); });

OR you might want to consider using accordian instead, heres a demo

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Untitled Document</title><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script><script type="text/javascript">/*<![CDATA[*//*---->*/$(function() {$( "#accordion" ).accordion();});/*--*//*]]>*/</script>  <style type="text/css"></style></head><body><div class="demo"> <div id="accordion"><h3><a href="#">Section 1</a></h3> <div style="height:20px;"><p>Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integerut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sitamet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo utodio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.</p></div><h3><a href="#">Section 2</a></h3><div><p>Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit ametpurus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitorvelit, faucibus interdum tellus libero ac justo. Vivamus non quam. Insuscipit faucibus urna.</p> </div><h3><a href="#">Section 3</a></h3><div><p>Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac liberoac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quislacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.</p><ul><li>List item one</li> <li>List item two</li><li>List item three</li></ul></div><h3><a href="#">Section 4</a></h3><div><p> Cras dictum. Pellentesque habitant morbi tristique senectus et netuset malesuada fames ac turpis egestas. Vestibulum ante ipsum primis infaucibus orci luctus et ultrices posuere cubilia Curae; Aenean laciniamauris vel est.</p><p>Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.Class aptent taciti sociosqu ad litora torquent per conubia nostra, perinceptos himenaeos.</p></div></div> </div><!-- End demo -->  </body></html>

Edited by dsonesuk

Share this post


Link to post
Share on other sites

dsonesuk, This is EXACTLY what i wanted from the beginning. I did not know it could be accomplished so easy-with so few lines of code, no loops involved at all.(i use the first code segment) I am an amateur in jQuery, just now i am starting to grasp it. Again, thanks.

Share this post


Link to post
Share on other sites

Just a improvement on the code, at present the code will make one show_hide remain open all the time, and when clicked it will slide up then down. to only target show_hide container other than the one clicked use not(), this will prevent jumping up and down, and let you be able to close all show_hide containers

$(document).ready(function(){$("div.show_hide").hide();$(".testMenuItem1").click(function (){//$("div.show_hide").hide();// old//$("div.show_hide").slideUp("medium"); //old$("div.show_hide").not($(this).next("form").children("div.show_hide")).slideUp("medium"); // new//$("div.show_hide").not($(this).next("form").children("div.show_hide")).hide(); //new$(this).next("form").children("div.show_hide").slideToggle("slow");});});

Share this post


Link to post
Share on other sites

Yes, this improvement was needed,now the whole thing is complete. Thanks Dsonesuk

Share this post


Link to post
Share on other sites

Sorry for coming again to the topic.I am trying to understand the logic behind this jQuery code:

$("div.show_hide").not($(this).next("form").children("div.show_hide")).slideUp("medium");

I am having difficulty understanding it well. So far i have managed to understand quite well what the .not does(the filtering).But there are some details that confuse me.What we achieved with the above code was to slideup .div.show_hide when we are clicking another a element(so as to open the specific div_show_hide).What i cannot understand id how .not($(this).next("form").children("div.show_hide")). help us achieve that.It seems that .not($(this).next("form").children("div.show_hide")). comes in contrast with ("div.show_hide") which precedes it.From one point we select ("div.show_hide") and from the other we do not, by employing.not($(this).next("form").children("div.show_hide")).Sorry for the lengthy message.

Share this post


Link to post
Share on other sites

If you use the original script it will close ALL element with class show_hide, which causes the current targeted show.hide toggle function to reset to slideup, then it triggers this function changing it to slide down, that why it quickly slides up and then down again, and you cannot close/slideup this element without it sliding down again. The new code targets all class show_hide EXCEPT itself, and resets there toggle to closed/slideUP, The current toggle has has not been changed so it knows at present it is open, and by clicking it, it again is ignored because of the .not() function and closes as normal.

Edited by dsonesuk

Share this post


Link to post
Share on other sites

Now i think i am getting somewhere. So, you are saying that not($(this).next("form").children("div.show_hide")) targets the currently open div.show_hide, correct?

Edited by jimfog

Share this post


Link to post
Share on other sites

Yep! that's it to break it down Remember $(this) represents .testMenuItem1 being clicked $("div.show_hide").not($(this).next("form").children("div.show_hide")).slideUp("medium"); $("div.show_hide") = targets All 'div.show_hide' .not($(this).next("form").children("div.show_hide")) But not the (currently clicked element (.testMenuItem1)-> Next found Form Element -> CHILD element div with classname .show_hide). .slideUp("medium"); With the others apply slideUp.

Edited by dsonesuk

Share this post


Link to post
Share on other sites

Very good explanation, i think we are OK now. One reason i could not understand was because i did not pay attention as i ought to, to the this keyword. I missed that, the fact i mean that .this refers to the clicked item. If is there is something else i will let you know. Thanks AGAIN.

Share this post


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...