simple div onclick show javascript

为君一笑 提交于 2019-12-01 04:12:36

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

Here's a version without using a global (other than the function itself). The variable is held on the function object:

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

You need in your showdiv() first make all your elements display = "none"; And then make selected element display = "block";

You can also organize it in two functions hidealldivs(), which will hide all divs and your current showdiv(), which will show selected.

Then onClick call both of them one after another

onclick="hidealldivs(); showdiv('eating')"

You need to initially hide your divs. Either in the StyleSheet or inline.

.patientinfodivs {
    display: none;
}

<div id="firstimpression" class="patientinfodivs" style="display: none;">
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!