Search code examples
jqueryclassscrolltagname

Scroll to specific tag name with specific class


Here is what my html code looks like :

<div class="code">
    <declaration class="2">
        toto
    </declaration>
    <identifier class="2">
        toto
    </identifier>
    <identifier class="3">
        toto
    </identifier>
    <identifier class="2">
        toto
    </identifier>
</div>

And here is my javascript :

function gotoDeclaration(){
    $(".code identifier").click(function goto() {
        var list = document.getElementsByClassName($(this).attr('class'));
        for (var i = 0; i < list.length; i++) {
            if (list[i].nodeName === 'declaration')
                $('html, body').animate(
                    {scrollTop: list[i].offset().top}, 
                    'fast');
            return false;
        }
    });
}

What I would like to do is that if I clic on an element with tag name identifier, it scrolls to the element with tag name declaration, with the same class as the identifier element.

Nothing happens when I clic.

The function is called just after with some others working functions :

$(document).ready(function(){
gotoDeclaration();
highlightIdentifiers();
expandCollapse();
});

Solution

  • Doing list[i] return an HTML element. The problem is that you are using a jQuery function with that: list[i].offset().

    To solve that, use .eq instead:

    $('html, body').animate(
        {scrollTop: list.eq(i).offset().top}, 
        'fast');
    

    There is also a better way to code that. Since jQuery is already loaded, use it!

    function gotoDeclaration(){
        $(".code identifier").click(function goto() {
            var list = $('declaration.'+$(this).attr('class'));
            $('html, body').animate(
                 {scrollTop: list.offset().top}, 
                 'fast');
        });
    }