Search code examples
javascriptmethodsjquery-click-event

How to differentiate the click event based on clicked DOM node?


How can I change the method's behavior based on which node was clicked? I want to change the data attribute's value to 0 if the $('.parent') was clicked.

$('.parent').on('click', function (event) {
    this.someClickFunction(event);
});

$('.child').on('click', function (event) {
    this.someClickFunction(event);
});

someClickFunction: function (event) {
    //TODO: If $('.parent') was clicked, change to 0
    $('.holder').data('type', 1);
}

Solution

  • You can use .is(selector) to check which element was clicked.

    Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

    For simplicity I have passed the function reference to click handler.

    $('.parent').on('click', this.someClickFunction);
    $('.child').on('click', this.someClickFunction);
    
    
    someClickFunction: function (event) {
        $('.holder').data('type', $(event.target).is('.parent') ? 1: 0);        
    }
    

    A good read Difference between $(this) and event.target?