zanderwar
zanderwar

Reputation: 3730

Determine clicked child whilst it's parent has it's own click listener

I have multiple accordion widgets on page.

To elaborate on how it's all setup

Is it possible to get the ACTUAL element that was clicked so that I can check that it was not the edit/save/discard etc buttons?

My accordion JS is:

this.accordion = function () {
    var element = $('.accordion > .panel-heading');

    element.on('click', function () {
        var self = $(this);
        if (self.hasClass('open')) {
            self.parent().find('.panel-body').stop().slideUp();
            self.find('.fa-caret-down').removeClass('fa-caret-down').addClass('fa-caret-up')
            self.removeClass('open');
            return;
        }

        self.addClass('open');
        self.find('.fa-caret-up').removeClass('fa-caret-up').addClass('fa-caret-down')
        self.parent().find('.panel-body').stop().slideDown();
    });
}

My obviously incomplete "Edit" JS is:

this.editableWidgets = function () {

    var edit = $('.panel .widgetBtn_edit');
    var save = $('.panel .widgetBtn_save');
    var discard = $('.panel .widgetBtn_discard');

    edit.on('click', function () {
        $(this).hide();
        $(this).next('.widgetBtn_save').show();
        $(this).next().next('.widgetBtn_discard').show();
    });

    save.on('click', function () {
        alert('hook up saving functionality')
    })

    discard.on('click', function () {
        $(this).hide();
        $(this).prev('.widgetBtn_save').hide();
        $(this).prev().prev('.widgetBtn_edit').show();
    })

}

Fig 1

Before = Before clicking Edit

After = After clicking Edit

Figure 1

Upvotes: 0

Views: 55

Answers (1)

kapantzak
kapantzak

Reputation: 11750

In order to get the actual element that was clicked you can use the event's target property.

In the following example try clicking on the bordered div and on the green span and see the different ids alerted:

//Event listener on outer element (#outer)
$(document).on('click', '#outer', function(e) {
  //e.target gets the actual element clicked
  var trg = e.target;
  var id = $(trg).attr('id');
  alert(id);
});
#outer {
  padding:10px;
  border: 1px solid #d8d8d8;
}

#inner { background-color:green; color:#fff }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer">
  Outer
  <span id="inner">Inner</span>
 </div>

Upvotes: 2

Related Questions