Alon Shmiel
Alon Shmiel

Reputation: 7121

Capturing and bubbling events

I created the next jsfiddle:

http://jsfiddle.net/AHyN5/6/

This is my code:

var mainDiv = document.getElementsByClassName('mainDiv');
var div = mainDiv[0].getElementsByClassName('data');

mainDiv[0].addEventListener("click", function(e) {
     alert('1');
});

$(mainDiv[0]).children('img').click(function (e) {
    e.stopImmediatePropagation()
     return false;    
})

I want that click on the pink background will popup a message with value of 1(an alert message).

When clicking the yellow, I want nothing to happen.

I read this blog but with no success..

Any help appreciated!

Upvotes: 0

Views: 28

Answers (3)

murmeister
murmeister

Reputation: 672

I agree with the others stating to use jQuery or straight DOM calls.

Here is another shot at the jQuery solution - very similar to the one above. I went ahead and presented it because it targets the images directly - in case that's what you're really trying to accomplish.

$(function()
{   var mainDiv = $('div.pink:first'),
        imgs = $('img');

    mainDiv.click(function()
    {   alert('1');
    });

    imgs.click(function(e)
    {   e.stopImmediatePropagation();
    });
});

Upvotes: 1

leo.fcx
leo.fcx

Reputation: 6467

You have a mix of jQuery and DOM methods calls. Note also that for attaching event listeners, you should wait for all HTML document to be ready.

I'd recommend using either DOM methods ot jquery methods. Following is an example of jquery:

$(function(){
    $('.pink:first').on("click", function(e) {
         alert('1');
    });

    $('.yellow').on('click', function (e) {
        e.stopPropagation();
    });
})

See also this JSfiddle

Upvotes: 0

Ed Ballot
Ed Ballot

Reputation: 3485

You could add pointer-events: none; to the yellow class. That will cause those elements to not fire click events.

See here for more info https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

Upvotes: 0

Related Questions