Thomas Lai
Thomas Lai

Reputation: 317

have parent div clickable with clickable child div

How do I do something like:

<div onclick="foo1()">
    <div onclick="foo2()"></div>
</div>

When I do that and I click the child element, it still runs the foo1() function. How do I temporarily disable the parent element or something?

Upvotes: 2

Views: 4503

Answers (4)

Thanos
Thanos

Reputation: 3059

I have created a working EXAMPLE for you

HTML

<div id="parent">
    <div id="child"></div>
</div>

CSS (just to distinguish the two divs)

#parent {
    background-color: black;
    width: 220px;
    height: 220px;
}

#child {
    position:relative;
    background-color: blue;
    width: 110px;
    height: 110px;
    top:160px;
    left:160px;
}

JavaScript ( include jQuery )

$(document).ready(function(){
    $('#child').click(function() {
        alert('Child');
        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
    });
    $('#parent').click(function() {
        alert('Parent');
    });
});

When you click on the child ONLY the action from the child is getting actioned. You can modify my example as you like to achieve what you need.

Hope this works for you.

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

You can try

<div onclick="foo1(event)">
    parent
    <div onclick="foo2(event)">child</div>
</div>

And

function foo1(e){
    console.log('foo1', e)
}

function foo2(e){
    e.stopPropagation();
    console.log('foo2', e)
}

Demo: Fiddle

Upvotes: -1

shairya
shairya

Reputation: 183

Yes, jQuery can solve your problem. See the code below:

<script src="jquery.js" type="text/javascript"></script>
<script>
function a()
{
    alert('parent');
}

$(document).ready(function(){
    $('#div2').click(function(e){alert('child');e.stopPropagation();})
})
</script>
<div onclick="a();" style="height:100px;width:100px;border:1px solid red">
    <div id="div2" style="height:85px;width:85px;border:1px solid green">
    </div>
</div>

Upvotes: 1

Matej Chrenko
Matej Chrenko

Reputation: 188

With jQuery, you can use this: http://api.jquery.com/event.stopPropagation/

Upvotes: 3

Related Questions