Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript functions to show and hide divs

Hello I have the following 2 JavaScript functions to open up a div and to close it.

<script>
    function show() {
        if(document.getElementById('benefits').style.display=='none') {
          document.getElementById('benefits').style.display='block';
        }
    }
</script>



<script>
    function close() {
        if(document.getElementById('benefits').style.display=='block') {
          document.getElementById('benefits').style.display='none';
        }
    }  
</script>

Here is the html:

<div id="opener"><a href="#1" name="1" onclick=show()>click here</a></div>
<div id="benefits" style="display:none;">
   some input in here plus the close button
   <div id="upbutton"><a onclick=close()></a></div>
</div>

For some reason the show function works how it should, but the close button does not do its job. So if there is someone who could help me out I really would appreciate. Thanks a lot.

like image 504
bonny Avatar asked Jul 09 '12 12:07

bonny


3 Answers

<script> 
    function show() { 
        if(document.getElementById('benefits').style.display=='none') { 
            document.getElementById('benefits').style.display='block'; 
        } 
        return false;
    } 
    function hide() { 
        if(document.getElementById('benefits').style.display=='block') { 
            document.getElementById('benefits').style.display='none'; 
        } 
        return false;
    }   
</script> 


 <div id="opener"><a href="#1" name="1" onclick="return show();">click here</a></div> 
    <div id="benefits" style="display:none;">some input in here plus the close button 
           <div id="upbutton"><a onclick="return hide();">click here</a></div> 
    </div> 
like image 70
WolvDev Avatar answered Oct 18 '22 02:10

WolvDev


I usually do this with classes, that seems to force the browsers to reassess all the styling.

.hiddendiv {display:none;}
.visiblediv {display:block;}

then use;

<script>  
function show() {  
    document.getElementById('benefits').className='visiblediv';  
}  
function close() {  
    document.getElementById('benefits').className='hiddendiv';  
}    
</script>

Note the casing of "className" that trips me up a lot

like image 45
PaulMolloy Avatar answered Oct 18 '22 03:10

PaulMolloy


The beauty of jQuery would allow us to do the following:

$(function()
{
    var benefits = $('#benefits');

    // this is the show function
    $('a[name=1]').click(function()
    { 
        benefits.show();
    });

    // this is the hide function
    $('a', benefits).click(function()
    {
        benefits.hide();
    });
});

Alternatively you could have 1 button toggle the display, like this:

$(function()
{
    // this is the show and hide function, all in 1!
    $('a[name=1]').click(function()
    { 
        $('#benefits').toggle();
    });
});
like image 42
Richard Avatar answered Oct 18 '22 02:10

Richard