I have repeated down the page an image with a div next to it like this:
<img src="/img/productspage/questionMark.jpg" class="prodQuestionMark" />
<div class="vuQuestionBubble">
<p>this is where text for the text will go</p>
</div>
vuQuestionBubble has a style display:none by default. when 'prodQuestionMark' is clicked i want the vuQuestionBubble next to it to show. ive put this code at the bottom.
$(document).ready(function () {
$('.prodQuestionMark').click(function () {
$(this).closest('vuQuestionBubble').show();
});
});
it doesn't seem to work... the click event is working and i can select the parent div with .parent but cant seem to interact with the closest div... any ideas?
closest looks for ancestors, not siblings; also, your selector is missing a . at the beginning (you're telling it to look for a vuQuestionBubble element, where you really mean a div with the class "vuQuestionBubble").
With your current structure, you can use next because the div with the "vuQuestionBubble" is the very next element. However, if you ever change your structure and put something between them, next won't work for you.
I'd probably use nextAll("div.vuQuestionBubble:first") or nextAll(".vuQuestionBubble:first") (links: nextAll, :first):
$(document).ready(function () {
$('.prodQuestionMark').click(function () {
$(this).nextAll('div.vuQuestionBubble:first').show();
// Or without `div`:
//$(this).nextAll('.vuQuestionBubble:first').show();
});
});
That will find the first div with the class "vuQuestionBubble" that follows the img as a sibling, even if it's not the one right next to the img, and so makes your code less susceptible to maintenance issues if the markup changes slightly.
The closest function finds the closest ancestor to the element. You actually need to use .next('.vuQuestionBubble').
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With