简体   繁体   中英

Showing/hiding <div> with JavaScript

I wrote simple JavaScript to show hidden <div> after clicking another <div> . Everything works fine however when clicking checkbox in that <div> the hidden one appears and hides instantly.

 $(document).ready(function() { $('#click1').click(function() { if ($('#hidden1').is(':hidden')) { $('#hidden1').show(500); } else { $('#hidden1').hide(500); } }); }); 
 .divCell { width: 500px; height: 35px; margin: 2px 0; display: inline-block; background-color: #D4F78F; } .checkbox_div { width: 25px; position: relative; margin: 5px; float: left; } input[type="checkbox"] { display: none; } input[type="checkbox"] + label { width: 25px; height: 25px; cursor: pointer; position: absolute; top: 0; left: 0; background-color: white; border-radius: 4px; } .div_name_divcell { line-height: 35px; width: auto; float: left; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <div class="divCell" id="click1"> <div class="checkbox_div"> <input type="checkbox" id="checkbox1"> <label for="checkbox1"><span></span> </label> </div> <div class="div_name_divcell">Name1</div> </div> <div id="hidden1" style="display: none;"> hidden text </div> 

Fiddle: https://jsfiddle.net/mamzj4tw/

Add event.preventdefault to your code

  $(document).ready(function() {
  $('#click1').click(function(event) {
  event.preventDefault();


        if ($('#hidden1').is(':hidden')) {

       $('#hidden1').show(500);
    } else {

       $('#hidden1').hide(500);
    }
  });
});

Here is the Fiddle: https://jsfiddle.net/mamzj4tw/1/

You can use just return false;

$(document).ready(function() {
  $('#click1').click(function() {
    if ($('#hidden1').is(':hidden')) {
      $('#hidden1').show(500);
    } else {
      $('#hidden1').hide(500);
    }
    return false;
  });
});

https://jsfiddle.net/shadiq_aust/m91wf79y/1/

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