simple div onclick show javascript

user813032 picture user813032 · May 6, 2012 · Viewed 88.9k times · Source

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>

Answer

Nick picture Nick · May 6, 2012

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';
}