1

I'm using jQuery .attr() method to get the value of an element's attribute, in this case an id, and storing it into a string. Then I replace "info" to "article" in the string to hide and show elements in my page.

My HTML code looks like this:

<div id="navigator">
    <div id="info_01"><a href="#">Lorem Ipsum</a>
        <div id="info_02"><a href="#">Lorem Ipsum</a></div>
    </div>
    <div id="info_03"><a href="#">Lorem Ipsum</a></div>
</div>

jQuery code:

    $('#navigator>div, #navigator>div>div').click(function(){
    var variable=$(this).attr('id');
    var variable2=(variable.replace("info", "article"));
    console.log(variable2);

    $("#another_div").hide();
    $("#"+variable2).show();
});

I'm outputting log to console, and when I click on parent divs inside #navigator such as #info_01 and #info_03 it prints only the id of the div I clicked, but when I click on child elements in #navigator such as #info_02, it prints two lines:

article_02
article_01

As you can see, the first one is from the first div I click on, but since I'm also clicking on its parent, it outputs the parent's id.

I only need to output one id, the one from the element I click on, and not its parent's id.

How can I do that?

Guado
  • 13
  • 3
  • This should help http://www.quirksmode.org/js/introevents.html. Look for "event propagation". Also I suggest you use a common class instead of id's. – elclanrs Dec 01 '13 at 21:35
  • i think that the thing you are trying to achieve can be done in a simpler way if explaing clearly what exactly you are trying to do.. – HIRA THAKUR Dec 01 '13 at 21:37
  • Thanks, elclanrs. Useful and simple answer. – Guado Dec 01 '13 at 21:42
  • possible duplicate of [Prevent execution of parent event handler](http://stackoverflow.com/questions/1398582/prevent-execution-of-parent-event-handler) – Felix Kling Dec 01 '13 at 21:42
  • To get the id from the element clicked, just use the event.target instead ? – adeneo Dec 01 '13 at 21:47

1 Answers1

2

Use .stopPropagation(). This prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. Read more on https://api.jquery.com/event.stoppropagation

$('#navigator>div, #navigator>div>div').click(function(e){
    var variable=$(this).attr('id');
    var variable2=(variable.replace("info", "article"));
    console.log(variable2);

    $("#another_div").hide();
    $("#"+variable2).show();
    // propagate
    e.stopPropagation();
});
nu everest
  • 9,589
  • 12
  • 71
  • 90
Pejman
  • 2,442
  • 4
  • 34
  • 62
  • Could you explain why e.stopPropagation() is necessary? – nu everest Aug 16 '17 at 17:04
  • @nueverest `stopPropagation()` Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. read more on https://api.jquery.com/event.stoppropagation/ – Pejman Aug 17 '17 at 06:24