Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
160
rated 0 times [  161] [ 1]  / answers: 1 / hits: 116072  / 11 Years ago, tue, october 29, 2013, 12:00:00

I have one html div on my jsp page, on that i have put one anchor tag, please find code below for that,



<div class=expandable-panel-heading>
<h2>
<a id=ancherComplaint href=#addComplaint
onclick=markActiveLink(this);>ABC</a>
</h2>
</div>


js code



$('.expandable-panel-heading:not(#ancherComplaint)').click(function () {
alert('123');
});

function markActiveLink(el) {
alert($(el).attr(id));
}


here I when I click on div I got alert with 123 message, its fine but when I click on ABC I want message I want to call markActiveLink method.



JSFiddle



what is wrong with my code? please help me out.


More From » jquery

 Answers
17

The problem was that clicking the anchor still triggered a click in your <div>. That's called event bubbling.



In fact, there are multiple solutions:




  • Checking in the DIV click event handler whether the actual target element was the anchor

    → jsFiddle



    $('.expandable-panel-heading').click(function (evt) {
    if (evt.target.tagName != A) {
    alert('123');
    }

    // Also possible if conditions:
    // - evt.target.id != ancherComplaint
    // - !$(evt.target).is(#ancherComplaint)
    });

    $(#ancherComplaint).click(function () {
    alert($(this).attr(id));
    });

  • Stopping the event propagation from the anchor click listener

    → jsFiddle



    $(#ancherComplaint).click(function (evt) {
    evt.stopPropagation();
    alert($(this).attr(id));
    });





As you may have noticed, I have removed the following selector part from my examples:



:not(#ancherComplaint)


This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.



I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.


[#74651] Monday, October 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackie

Total Points: 442
Total Questions: 107
Total Answers: 94

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
jackie questions
Sat, Sep 18, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
;