I was working on a simple show and hide function and it kept telling me that it's not defined.
Here's the HTML:
<address>
<a id="windows" href="#" onclick="toggle();">
<img src="imges/c980e3f5-badf-432a-ae6c-9e5341d13462.png" alt="" />
</a>
</address>
<p class="right_page">
this is sample of the book container<br/>
thats suppose to read from ajax
</p>
and here the function
<script type="text/javasript">
function toggle()
{
var ele = document.getElementById("right_page");
var text = document.getElementById("windows");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
</script>
-
Please post the exact error message you're getting (i.e. what exactly is not defined).August Lilleaas– August Lilleaas2011年07月18日 08:07:48 +00:00Commented Jul 18, 2011 at 8:07
-
did you define the function in the head of the document?Ibu– Ibu2011年07月18日 08:08:06 +00:00Commented Jul 18, 2011 at 8:08
-
Try to debug with getfirebug.comyogs– yogs2011年07月18日 08:09:36 +00:00Commented Jul 18, 2011 at 8:09
-
thats the error toggle is not definedAly_Elgahy– Aly_Elgahy2011年07月18日 08:09:57 +00:00Commented Jul 18, 2011 at 8:09
-
i define the function on the html bodyAly_Elgahy– Aly_Elgahy2011年07月18日 08:10:23 +00:00Commented Jul 18, 2011 at 8:10
3 Answers 3
I think it is due to a typo in your script tag. Change type="text/javasript" to type="text/javascript" (missing the c).
Update
Your image is being removed from the DOM due to you setting the innerHtml to a string. This overwrites the image which is part of the innerHtml.
The first time that you run toggle() there is not an inline style for display so ele.style.display will be an empty string. This means that it will drop into the logic for showing the paragraph. On subsequent calls the property will have a value so it should behave as you expect.
2 Comments
div also have the ID windows? IDs have to be unique.There are a couple of things wrong here:
Did you paste this in directly from your code? If so, your
<script type...line contains a typo (should be "javas*c*ript")You can't use
getElementById()forright_pageas it stands, becauseright_pageis only defined as a class in your mark-up.
1 Comment
innerHTML on windows means that your image is effectively removed from the page and replaced with some text.First you missed the C change type="text/javascript", second the right_pae is not a ID,
can't use document.getElementById because there are something wrong with your function, so it tells you the function is undefined