2

I have the following HTML:

<div class="eventContainer" id="dennaVecka" style="background-color: #2B4699;">
    <p>Denna vecka</p>
</div><!--eventContainer ends--> 
<div class="eventList" id="dennaVecka_table">
...
</div>

And the following jQuery:

eventID = null;
$('.eventContainer p, .eventContainer').click(function (e) {
//eventID = $(this).attr('id');
eventID = e.target.id;
$('.eventList#' + eventID + '_table').fadeIn(300);
//alert(e.target.id);
});

I want: When div class eventContainer or the paragraph inside it is clicked, I want to use the ID of eventContainer (id="dennaVecka") to display the div class eventList beneath it. My problem with the current setup is that I don't know how to get the ID of eventContainer if the paragraph is clicked. If I click the paragraph I will get the ID of the paragraph ("undefined").

Is there a way to get the ID of eventContainer in jQuery no matter if I click the div or the paragraph?

Maybe I should setup the HTML in another way?

1 Answer 1

2

Use the fact that click event bubbles up to the parent container. In this case you can bind only one event handler to .eventContainer and read this.id to get container id:

$('.eventContainer').click(function (e) {
    eventID = this.id;
    $('.eventList#' + eventID + '_table').fadeIn(300);
});

So if you click p element inside .eventContainer event will still be handled by above listener on .eventContainer, with this pointing to it.

Sign up to request clarification or add additional context in comments.

2 Comments

Works! Thank you! Is it calling the .eventContainer-selector which makes the bubbling stop here and show that ID and for example not the ID of the parent of .eventContainer?
When you click p element inside .eventContainer this event is not handled by anything (you don't bind events to p). However click event bubble up to the parent, then to the next parent untill it reaches html element. You bind click event to .eventContainer so it will detect events on child p element also, because this event eventually bubbles up to it. From there you can get id reliably.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.