Hank
Hank

Reputation: 569

Toggle next element only works within divs

I have an article written and would like the hyperlink footnotes to toggle their corresponding references inline. So, example:

jQuery:

$(document).ready(function() {
    $('.reference').hide();
    $('.footnote').click(function() {
        $(this).next('.reference').toggle('slow');
        return false;
    });
});

html:

<p>
    Blah blah blah blah<a href='#' class='footnote'>[5]</a><span class='reference'>Doe, John. <em>The Book of Blah</em>. 2013.</span>
</p>

Which works fine—but in certain cases where formatting is an issue, putting the reference span outside of the paragraph tags screws up the whole operation.

<p>
    Blah blah blah blah<a href='#' class='footnote'>[5]</a>
</p>
<span class='reference'>Doe, John. <em>The Book of Blah</em>. 2013.</span>

Any ideas?

Thanks!

Upvotes: 0

Views: 323

Answers (2)

Andy
Andy

Reputation: 30135

http://api.jquery.com/next/

Description: Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

This means your code: $(this).next('.reference').toggle('slow'); will only select a .reference element immediately following this. In your example .footnote.

This isn't the case in your second example, since .footnote is the last element in its parent. To make it work you'd have to do something like this:

$(this).parent().next('.reference')

Upvotes: 1

Romain Paulus
Romain Paulus

Reputation: 2368

If you want this to be really flexible, you should put the footnote number inside the footnote tag and the reference tag:

<p>
    Blah blah blah blah<a href='#' data-footnote="5" class='footnote'>[5]</a>
</p>
<span class='reference' id='reference-5'>Doe, John. <em>The Book of Blah</em>. 2013.</span>

As for the javascript:

$(document).ready(function() {
    $('.reference').hide();
    $('.footnote').click(function() {
        $('#reference-' + this.getAttribute('data-footnote') ).toggle('slow');
        return false;
    });
});

Upvotes: 1

Related Questions