Reputation: 2021
i have some trouble here using js/jquery:
I have parent LIs with several different child elements in it. Now every child element has an own attached event-handler. What i need now is to call an event of the parent if it misses some class, and call the (clicked) child's event if the parent has that class:
<div id="parent" class="expanded">
<span class="child1"></span>
<div class="child2"></div>
<font class="child3"></font>
</div>
Now i only want to execute each child-events if the parent container misses the class "expanded". If the parent is "expanded" i need to allow the executed functions.
Now sure it's easy to ask for that class in every single handler on the child elements, but i think there could be a much better solution using only one handler that decides and bubbles/stopBubble the event. Do you know any nice solution?
Easy to say, the key is Capturing. Since jQuery does not support capturing (bubbling the other direction: From parent to child) i can use this workaround:
Now it works adding this to the beginning of my code:
$('#parent').get(0).addEventListener('click', function(e) {
if(!$(this).closest('li').hasClass('expanded')) {
e.stopPropagation();
e.preventDefault();
e.stopImmediatePropagation();
return getTicket(e, $(this)).toggleVisibility();
}
}, true);
Upvotes: 2
Views: 4809
Reputation: 4539
Alternatively you can use .parent().not() api to achieve your objective; like below:
$(".child").parent().not(".expanded").click(function(){
// code to parent which is not having class expanded should go here.
}
Upvotes: 1
Reputation:
If you have separate child event handlers already defined;
You can create a generic child event handler and throw a user exception(When its parent is not expanded) to prevent further child-specific events
$(".child").on("click", function (e) {
//If parent does not have class expanded
if (!$(this).parent().hasClass("expanded"))
throw {}
});
/* Child handlers already defined */
$("span.child").on("click", function (e) {
console.log('span');
});
$("div.child").on("click", function (e) {
console.log('div');
});
/**/
Upvotes: 1
Reputation: 13049
$(".child").click(function(){
if($(this).parent().hasClass("expanded"))
{
//do parent stuff with $(this).parent()
}
else
{
//do child stuff with $(this)
}
});
Upvotes: 4