jquery - 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 setup
- the green heading shown in image below, handle jquery ui sortable
- the green heading has click listener collapses/expands accordion.
- the edit button has it's own click listener when fired intended fire listener collapse accordion
is possible actual element clicked can check not 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 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 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
in order actual element clicked can use event's target
property.
in following example try clicking on bordered div , on green span , see different ids alerted:
//event listener on outer element (#outer) $(document).on('click', '#outer', function(e) { //e.target gets 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>