herrsaidy
herrsaidy

Reputation: 91

anchor with url don't work with onclick event

i have a link to scroll to top

<a href="index.html?test=test#slides-1" id="re" class="ancLinks"></a>
$("a.ancLinks").click(function (){
            elementClick = $("this").attr("href");
            $('html, body').animate({
            scrollTop: $(elementClick).offset().top
            }, 1000);
        });

when I take out the url (index.html? test = test) it works. but I need absolutely link in the url. what is wrong

Upvotes: 0

Views: 85

Answers (2)

ReSpawN
ReSpawN

Reputation: 689

You are trying to get the offset position of an element which comes down to "index.html?test=test#slide-1", which is not an element but a URI.

The element offset should be fetched from a real DOM element, possibly the target. You can simply achieve this by doing something like this:

$('a.ancLinks').click(function(event) {
    var $this = $(this),
        href = $this.attr('href'),
        target = $this.data('target') || (href.indexOf('#') !== -1 ? '#'+href.split('#').pop() : false);

    if (!target) return true;
    var $target = $(target);

    if ($target.length == 0) return true;
    event.preventDefault();
    var offset = $target.offset();

    $('html, body').animate({
        scrollTop: offset.top || 0
    });
});

This works with both <a href="anyurl.html#your-html-ID"> and <a href="anypage.html" data-target="#your-html-ID">

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

I think you want:

DEMO

$("a.ancLinks").click(function (e){
            e.preventDefault();
            elementClick = this.hash;
            $('html, body').animate({
            scrollTop: $(elementClick).offset().top
            }, 1000);
        });

Upvotes: 3

Related Questions