Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple div onclick show javascript

when I click on any link the correspoding div shows up but when I click the next link, the newly clicked dive shows up as well as the previously clicked. I would like the previos div to hide. NEW to development please some one help me........

this is the html code for links:

<a class="hide" onclick="showdiv('firstimpression'); " href="#">First Impression</a>
<a class="hide" onclick="showdiv('speaking'); " href="#">Speaking</a>
<a class="hide" onclick="showdiv('eating'); " href="#">Eating</a>
<a class="hide" onclick="showdiv('taste'); " href="#">Taste</a>
<a class="hide" onclick="showdiv('saliva'); " href="#">Saliva</a>
<a class="hide" onclick="showdiv('cleaning');" href="#">Cleaning</a>
<a class="hide" onclick="showdiv('nighttime');" href="#">Night Time</a>
<a class="hide" onclick="showdiv('singledenture');" href="#">Single Denture</a>
<a class="hide" onclick="showdiv('soreness');"  href="#">Soreness</a>
<a class="hide" onclick="showdiv('burning');" href="#">Burning</a>
<a class="hide" onclick="showdiv('adapting');" href="#">Adapting</a>
<a class="hide" onclick="showdiv('futureconsideration');" href="#">Future Consideration</a>
<a class="hide" onclick="showdiv('conclusion');" href="#">Conclusion</a>

these are the divs:

<div id="firstimpression" class="patientinfodivs">
<div id="speaking" class="patientinfodivs">

.....and so on

Javascript code

<script type="text/javascript">
function showdiv(id){
document.getElementById(id).style.display = "block";
}
</script>
like image 599
user813032 Avatar asked May 06 '12 03:05

user813032


People also ask

How do I make div appear and disappear on click?

The style. display = “none” will make it disappear when clicked on div.

How do I hide one div and show another div?

To show and hide div on mouse click using jQuery, use the toggle() method. On mouse click, the div is visible and on again clicking the div, it hides.


1 Answers

As much as I hate creating global variables, they just come in so handy sometimes...

var _hidediv = null;
function showdiv(id) {
    if(_hidediv)
        _hidediv();
    var div = document.getElementById(id);
    div.style.display = 'block';
    _hidediv = function () { div.style.display = 'none'; };
}

This will prevent you from needlessly searching through divs to find the one you should hide.

Edit: Expanding upon @StevenRoose's suggestion:

var _targetdiv = null;
function showdiv(id) {
    if(_targetdiv)
        _targetdiv.style.display = 'none';
    _targetdiv = document.getElementById(id);
    _targetdiv.style.display = 'block';
}
like image 156
Nick Avatar answered Sep 24 '22 08:09

Nick