2

I'm working on jQuery selector and getting this trouble:

<div class="pull-left">
    <span class="fa fa-circle"></span>
    <a class="name" href="#">User name</a>
</div>

pull-left class has the width 180px and name class has the width ~ 80px.

I want to write an event for pull-left class (except name class). I've tried:

$event.chatwindow = {
    resize: function () {
        let _this = $(this),
            chatwindow = _this.closest('.chat-window'),
            body_content = chatwindow.find('.body-content');

        // test while clicking on <a> tag
        // but always getting:
        // <div class"pull-left">...</div>
        $log(this);

        // avoid to click <a> tag
        if (!_this.hasClass('name')) {

            if (!body_content.hasClass('hidden')) {
                body_content.addClass('hidden');
            } else {
                body_content.removeClass('hidden');
            }

        }
    }
};

$(document).on('click', '.chat-window .header .pull-left', $event.chatwindow.resize);

But when I tried to click on the a tag, the window was still hidden/shown.

How can I run the event while clicking on pull-left div but avoiding <a> tag?

Thank you!

  • A good read to understand what really is happening may be this one : https://stackoverflow.com/a/1688293/5701319 , (hint : Event delegation / bubbling), you can indeed, as lucumt suggested use the event.stopPropagation() method to stop the event from 'bubbling' (going up to the parent by traversing each child) or from being delegated (going up to the child) (correct me if I'm wrong) – MaieonBrix Mar 31 '18 at 14:38

2 Answers2

0

this is the pull-left element.

Use the event target instead to check for which child was clicked

$event.chatwindow = {
    resize: function (event) {
        ....

        if(!$(event.target).hasClass('name') {
          // body class stuff 
        }

   }
}
charlietfl
  • 164,229
  • 13
  • 110
  • 143
-1

You can use jQuery event.stopPropagation() to do it

resize: function (event) {
    let _this = $(this),
        chatwindow = _this.closest('.chat-window'),
        body_content = chatwindow.find('.body-content');

    // test while clicking on <a> tag
    // but always getting:
    // <div class"pull-left">...</div>
    $log(this);

    // avoid to click <a> tag
    event.stopPropagation();
}
lucumt
  • 6,642
  • 2
  • 16
  • 32