Joshua Joshua - 3 months ago 7
HTML Question

how do I add a click attribute to a DIV without it applying to elements inside it?

I have a DIV that when clicked on expands to reveal some inputs and buttons, and will close when clicked on again, hiding those elements. The problem I am having is that when I click on the buttons or the input boxes the closing animation happens anyway. I know I can solve this by taking the inputs and buttons out of the DIV but the DIV is very important for their formatting and organization. Any help would be great, thanks!

html:

<div id='inputArea1' class='inputAreas'>
<input id='email' class='evInput' placeholder='example@gmail.com'>
<input id='comf' class='evInput' placeholder='Comfirmation Code'>
<button id='sndCde' class='evBut'>Send Code</button>
<button id='comfBut' class='evBut'>Comfirm</button>
</div>


JS:

var main = function() {
$('.box').click(function() {
var el = $(this);
if (!el.hasClass('selected')) {
el.animate({
"height": "300px"
}, 200)
el.addClass("selected");
el.find('.inputAreas').show();
} else {
el.animate({
"height": "85px"
}, 200);
el.find('.inputAreas').hide();
el.removeClass("selected");
}
})
}
$(document).ready(main);


FULL CODE: https://jsfiddle.net/dL2vzga0/

Answer

event.stopPropagation(); can do the job:

$('#inputArea1').click(function(event){
  event.stopPropagation();
});

Fixed Fiddle