Show / hide <div> using JavaScript
I wrote simple JavaScript to show a hidden <div> after clicking on another <div> . Everything works fine, but when you click the checkbox in the <div> 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> Violin: https://jsfiddle.net/mamzj4tw/
+5
2 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 script: https://jsfiddle.net/mamzj4tw/1/
+3