Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

event.preventDefault vs event.stopPropagation [duplicate]

Can someone explain what's the difference between event.preventDefault() and event.stopPropagation()?

I have a table and within that table I have an img tag.

When I click the img tag, I want to see a popup.

But I also want to stop the selection of multiple rows, so I use:

$("table.items tbody tr").click(function(event) {
        event.stopPropagation();
    });

When I use the js code, the popup does not appear;

If I delete the js code, the popup works.

$(".info").live("click",function(e){
    //console.log('ok');
    e.stopPropagation();
    var elem = $(this);
    var id = $(this).attr("id").replace("image_","container_");
    $('#'+id).toggle(100, function() {
        if($(this).css('display') == 'block') {
            $.ajax({
                url: "$url",
                data: { document_id:elem.attr('document_id') },
                success: function (data) {
                    $('#'+id).html(data);
                }
            });
            }
        });
});

Why?

like image 403
Ionut Flavius Pogacian Avatar asked Aug 09 '13 12:08

Ionut Flavius Pogacian


1 Answers

I am not a Javascript expert but as far as I know:

stopPropagation is used to make sure the event doesn't bubble up the chain. eg. a click on a <td> tag would also fire click events on it's parent <tr>, and then its parent <table>, etc. stopPropagation prevents this from happening.

preventDefault is used to stop the normal action of an element, eg. preventDefault in a click handler on a link would stop the link being followed, or on a submit button would stop the form being submitted.

like image 143
sevenseacat Avatar answered Sep 28 '22 08:09

sevenseacat