Reputation: 1700
I want to show the inner children of the div class {list} when use clicks on it, and when user clicks on it again, it will hide them. but the issue is when the user clicks on the input field it hides it back as-well .
<div class="list">
<label>Enter your name</label>
<input type="text" class="data"/>
</div>
<div class="list">
<label>Enter your Number</label>
<input type="text" class="data"/>
</div>
js code
$(document).ready(function()
{
$(".list").click(function(event){
$(this).children().slideToggle(1000);
});
});
Upvotes: 1
Views: 662
Reputation: 181
this is perfect example for usage function jQuery.delegate http://api.jquery.com/delegate/
You can specify parent element ('.list')
Then you will specify child objects in parent element ('label') where you want to use your "click" function. Watch out, function is called to "child element", so you need to toggle .parent() element
$(".list").delegate('label','click',function(event){
$(this).parent().slideToggle(1000);
});
Upvotes: 0
Reputation: 152
This because the event bubbles up when you click on the input element. You have to stop the event propagation of event by using the code line below:
evt.stopPropagation();
Upvotes: 0
Reputation: 4239
bind the click event to the input field and call event.stopPropagation().
Description: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
$(".list input").click(function(e){
e.stopPropagation();
});
or:
$(".list").click(function(){
$(this).children().toggle();
});
$(".list").children().click(function(e){
e.stopPropagation();
});
Upvotes: 2
Reputation: 129782
You could always check if the click is actually bubbled from a child node, and just drop it if it is:
$(".list").click(function(event){
if($(event.target).parents('.list').length > 0) { return; }
$(this).children().slideToggle(1000);
});
Another approach would be to manually cancel the bubbling, by calling event.preventDefault()
from the child nodes, but that may necessitate some extra care when you want other parts of the child nodes to be clickable.
Upvotes: 0