Welcome to WebmasterWorld Guest from 54.167.174.11

Forum Moderators: open

Message Too Old, No Replies

Hide and Display Div

hiding a displaying a div tag with javascript

   
7:12 pm on Mar 10, 2009 (gmt 0)

10+ Year Member



I'm making an faq page. When someone clicks on a question I want the answer to appear below it. This is what I've got so far, but it's not changing the style on click:

<script>
function displayAnswer($id) {
var status = document.getElementById($id).getAttribute("style");
if (status === "display:none;") {
document.getElementById($id).setAttribute("style","display:block;");
} else {
document.getElementById($id).setAttribute("style","display:none;");
}
}
</script>

This is the affected php code:
echo "<a href='javascript:displayAnswer({$faq[faq_id]});'>{$faq[question]}</a><br/>";
echo "<div id='{$faq[faq_id]}' style='display:none;'>{$faq[answer]}<br/></div>";

12:56 am on Mar 11, 2009 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



Try

function displayAnswer($id) {
var el = document.getElementById($id);
if ( el.style.display === "none") { el.style.display = "block" ); }
else { el.style.display = "none"); }
}

This does not rely on textual representations, edit case etc.
If it still don't work check php generated html.

1:19 am on Mar 11, 2009 (gmt 0)

10+ Year Member



I can't get that to work either:

<script>
function displayAnswer($id) {
var el = document.getElementById($id);
if ( el.style.display === "none") { el.style.display = "block" ); }
else { el.style.display = "none"); }
}
</script>
<a href="javascript:displayAnswer(2);">Some Question?</a><br/>
<div id="2" style="display:none;">Some Answer<br/></div>

3:11 am on Mar 11, 2009 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



id's should start with a letter, try adding a prefix say

<a href="javascript:displayAnswer("x2");">Some Question?</a><br/>
<div id="x2" style="display:none;">Some Answer<br/></div>

4:43 am on Mar 11, 2009 (gmt 0)

10+ Year Member



Thanks, this is working now:

<script>
function displayAnswer($id) {
var el = document.getElementById($id);
if (el.style.display === "none") {
el.style.display = "block"; } else {
el.style.display = "none"; }
}
</script>
<a href="javascript:displayAnswer('x2');">Some Question?</a><br/>
<div id="x2" style="display:none;">Some Answer<br/></div>