william44isme
william44isme

Reputation: 877

How to run javascript function when reaching an anchor tag?

Is it possible to run a javascript function when you pass a page section? What I am trying to achieve is something akin to Twitter Bootstrap's scrollspy.

Upvotes: 1

Views: 2124

Answers (3)

juan.facorro
juan.facorro

Reputation: 9930

Here's a fiddle that accomplishes the behavior you are looking for by registering a custom event on the a elements that's triggered based on a logic that you can customize as you see fit.

In the example the event is triggered when the a elements' position is within the range 0 to 100 from the top of the visible portion of the document.

JS

$(function() {
    $('a').on('reached', function() {
        alert('Reached ' + $(this).attr('id'));
    });
    $(document).on('scroll', function() {
        $('a').each(function() {
            var wt = $(window).scrollTop();
            var at = $(this).position().top;
            var dt = at - wt;
            if( dt >= 0 && dt < 100)
                $(this).trigger('reached');
        });
    });
})

Hope it helps.

Upvotes: 4

A. Wolff
A. Wolff

Reputation: 74410

You can use the waypoints plugin:

http://imakewebthings.com/jquery-waypoints/

Waypoints is a jQuery plugin that makes it easy to execute a function whenever you scroll to an element.

Upvotes: 6

pvnarula
pvnarula

Reputation: 2831

You can use scrollTop function of jQuery.

You can get the anchor tag position using position() function and tries to match it with scrollTop return value.

Upvotes: 3

Related Questions