Question

Is there a way to add a class to any div that is being scrolled to by clicking an anchor?

I currently have this code but can only add the "animated swing" class to the #ecomm div..

Ideally any anchor on the page that I click on I not only want to scroll down to it but add an animation class..

My code so far:

<script>
$('a[href=#ecomm]').click(function(){
  $("#ecomm").addClass( "animated swing" );
    $('html, body').animate({
    scrollTop: $( $.attr(this, 'href') ).offset().top
     }, 500);
     return false;
  });
</script>
Was it helpful?

Solution

Should work for all anchor tags with # hrefs.

<script>
    $('a[href^=#]').click(function () { // Use all anchor tags with an href that starts with #
        var href = $(this).attr('href'); // Get the href for the clicked anchor.
        $(href).addClass( "animated swing" ); // The href is the same as the id.
        $('html, body').animate({
            scrollTop: $(href).offset().top
        }, 500);
        return false;
    });
</script>

Taking into account @rorypicko's comment, a data attribute could be added to ensure only # hrefs you require will use this functionality:

<a href="#ecomm" data-scroll-link>Text</a>
<script>
    $('a[href^=#][data-scroll-link]').click(function () { // Use all anchor tags with an href that starts with # and the specified data attribute.
        var href = $(this).attr('href'); // Get the href for the clicked anchor.
        $(href).addClass( "animated swing" ); // The href is the same as the id.
        $('html, body').animate({
            scrollTop: $(href).offset().top
        }, 500);
        return false;
    });
</script>

OTHER TIPS

something like this:

<script>
    var href
    $('a').click(function(){
        href = this.attr('href');
        $('div').each(function(){
            var thisDiv = this
            if(this.attr('id') == href)
            {
                thisDiv.addClass( "animated swing" );
            }
            $('html, body').animate({
                scrollTop: thisDiv.offset().top
            }, 500);
        });
        return false;
     });
</script>


Hope this works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top