简体   繁体   中英

Simple way to .show .hide a #div onClick

I would like to have buttons that show divs when they are clicked and hide when clicked outside. (Anywhere on the page) The below code isn't working -- I'm not sure, why?

I'm trying;

<div class="side_button" id="side_button2">
TEXT 1
</div>

<div class="side_button" id="side_button3">
TEXT 2
</div>

CSS

#page_button2 {
    display: none;
    position: absolute;
    height: 300px;
    width: 400px;
    border: 1px dotted red;
    z-index: 999;
}

#page_button3 {
    display: none;
    position: absolute;
    height: 300px;
    width: 400px;
    border: 1px dotted red;
    z-index: 999;
}

.side_button { 
    height: 60px;
    border-bottom: 1px solid #333;
    color: #333;
    font-family: "KlavikaBasic-Bold";


    background-image: linear-gradient(bottom, #e5edda 6%, #fff 100%);
    background-image: -o-linear-gradient(bottom, #e5edda 6%, #fff 100%);
    background-image: -moz-linear-gradient(bottom, #e5edda 6%, #fff 100%);
    background-image: -webkit-linear-gradient(bottom, #e5edda 6%, #fff 100%);
    background-image: -ms-linear-gradient(bottom, #e5edda 6%, #fff 100%);

    background-image: -webkit-gradient(
    linear,
    left bottom,
    left top,
    color-stop(0.06, #dce6cc),
    color-stop(1, #fff)
   );


} 

JS

<script>

// Click to View Page
$(document).ready(function(){

$('#side_button2').click(function() {
    $('#page_button2').show();
    $('#page_button3').hide();
});

$('#side_button3').click(function() {
    $('#page_button3').show();
    $('#page_button2').hide();
});
// 

</script>

HTML

<!-- Show / Hide Div Side BTN -->

<div id="page_button2">
Test 1.
</div>

<div id="page_button3">
Test 2.
</div>

<!-- // Show / Hide Div Side BTN -->

As I said in my comment, it looks like you are missing }); to close the $(document).ready( . Without it, you are probably getting a syntax error

Try this:

$(document).ready(function(){

    $('#side_button2').click(function() {
        $('#page_button2').show();
        $('#page_button3').hide();
    });

    $('#side_button3').click(function() {
        $('#page_button3').show();
        $('#page_button2').hide();
    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM