user1432315
user1432315

Reputation: 117

Creating an anchor point on a div with an offset in JQuery

I am trying to get my link to go to an anchor point on another webpage, in this case a div with a unique id. However, as there is a menu with CSS positioning set as fixed (over the top of the div), I need to offset my positioning of where this 'top' is in effect. I have tried the following code but no luck. Any help welcome

 <a href="contact-us.html#book" class="book">Book a Place</a>  

with some JQuery as this in a document ready;

$('a[href^=".book"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': $target.offset().top
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });  

Upvotes: 1

Views: 207

Answers (1)

James Donnelly
James Donnelly

Reputation: 128791

$('a[href^=".book"]') attempts to select an a element whose href attribute begins with ".book". Your a element's href begins with "contact-us" and doesn't contain ".book" at all. .book by itself however is a class selector, and attempts to select the element whose class attribute is equal to "book". Therefore, I think what you meant to do was simply:

$('a.book').on('click',function (e) { ... })

After changing that, your a element has no hash property. To get the #book value from your a element's href you'd have to extract that separately. Bearing in mind that you'd have to already be on /contact-us.html for this to work, you could instead change your href to just #book:

<a href="#book" class="book"> ... </a>

Then pull the entire href:

var target = this.href;

Upvotes: 2

Related Questions