Playzare
Playzare

Reputation: 93

Jquery scroll to anchor only if id exists

I create a validation box when a form is complete, i reload the page to show it, and would like to automatically scroll to the validation box. I added an id to my box "invitation", and add this code in my js files :

$(document).scrollTop( $("#invitation").offset().top );

It works ! But when i'm on a page without the invitation id, my website is not working correctly.

How to scroll to this anchor only if it exists ?

Upvotes: 0

Views: 702

Answers (2)

charlietfl
charlietfl

Reputation: 171690

Wrap it in a conditional that checks length of the jQuery object. No length means no matching element found

var $invitation =  $("#invitation")
if($invitation.length){
   $(document).scrollTop( $invitation.offset().top );
}

Upvotes: 0

Shubham
Shubham

Reputation: 1288

Add it in if loop.

if ($("#invitation").length){
    $(document).scrollTop( $("#invitation").offset().top );
}

Upvotes: 1

Related Questions