Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 437
user2463248 Avatar asked Oct 19 '22 12:10

user2463248


1 Answers

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/

like image 165
Noah Telussa Avatar answered Nov 03 '22 22:11

Noah Telussa