neosan
neosan

Reputation: 366

Autoscroll page to Anchor under specific conditions

I have an account page with sidebar (in the photo)

enter image description here

I want the page to scroll automatically to #hello anchor in tablet and phone mode so in CSS @media 787

I can't find the appropriate jQuery or how to do it clearly.

I would like a modern and simple method

As I want this jQuery to run only in page account and in @media 787px it may be useful to specify this rule?

if you use a simple clean method, please share

Upvotes: 0

Views: 28

Answers (1)

Spectric
Spectric

Reputation: 31992

You can check whether the width of the viewport is smaller than 788px, and if so, set location.hash to the hello:

const width = $(window).width();

if(width < 788){
  location.hash = "hello";
}
#hello{
  margin-top:2000px;
  display:block;
}

html{
  scroll-behavior:smooth;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="hello" href="#">Hello World!</a>

Upvotes: 1

Related Questions