Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery closest doesn't want to work

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?

like image 904
phili Avatar asked Dec 17 '22 16:12

phili


2 Answers

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.

like image 183
T.J. Crowder Avatar answered Dec 19 '22 05:12

T.J. Crowder


The closest function finds the closest ancestor to the element. You actually need to use .next('.vuQuestionBubble').

like image 38
a'r Avatar answered Dec 19 '22 07:12

a'r