Koitoer Koitoer - 1 month ago 5
HTML Question

Detect click event in any nested element of an specific div

I need to be able to detect any click that happens within a specific container referenced by class, if the user clicks on any of the nested elements I should be able to detect the click and update a flag

<div class="container" >
<div class="x1">
<div class="x2">
<div class="">
<span class="">
<ul class="">
</div>
</div>


I tried using jquery but I prefer to do it using backbone.

//$(document).on('click','.container', function(e){
//$('.container').delegate("div", "click", function(e) {


Not sure what event I need to use when the users are clicking in some of the nested elements within the div that have the container class. Basically, I need to update a flag in case of the user clicks outside of this div, but I don't want to have a large scope on the event handler that listens to the whole body.

Answer

Since you asked for a Backbone example, here's how to listen to clicks on a div and its children.

var View = Backbone.View.extend({
    className: "my-test-view",
    template: '<div class="container"><div class="x1"><div class="x2">test</div></div></div>',
    events: {
        'click .container': 'onClick',
    },

    render: function() {
        this.$el.empty().append(this.template);
        return this;
    },

    onClick: function(e) {
        console.log("clicked on", e.target, " triggered from ", e.currentTarget);
    },
});

var view = new View();

$("body").append(view.render().el);

Clicking the test text should output:

clicked on <div class=​"x2">​test​</div>​  triggered from  <div class=​"container">​…​</div>​

With jQuery, the above is (roughly) the equivalent to:

$('.my-test-view').on('click', '.container', function(e) {
    console.log("clicked on", e.target, " triggered from ", e.currentTarget);
});

But for most case, this should be enough:

$('.container').on('click', function(e) {
    console.log("clicked on", e.target, " triggered from ", e.currentTarget);
});

Don't use .children().on(...) as this will create a now listener for each child and it's inefficient.

Detecting a click outside a div is quite different and there's many way to achieve it but none is perfect.

See :

Personally, I used focus and blur events (don't forget tabindex="-1" on the element).

Comments