Search code examples
htmljqueryjquery-selectorstoggle

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!


Solution

  • 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;
        });
    });