Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

365
Views
Scroll to a div using jQuery from other page

When I click href #demo-1 from home page to another page with ection id='demo-1'. How when loading the page with id='demo-1', that it will scroll down from the top of the page. If I use https://stackoverflow.com/a/3432718/6891215 it will jerk and not scroll from the top of the page down to that section.

Many thanks!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The code below allows you to scroll on both same and external pages. To make the link work you need to give it a class .scroll. If you're linking to an anchor link on an external page, give the link a data-target="external" as well.

$(document).ready(function() {
    $('html, body').scrollTop(0);
    var str = window.location.href;
    if(str.indexOf('#') > -1) {
        var anchor = str.substring(str.indexOf('#'));
        setTimeout(function() {
            $('html, body').animate({scrollTop: $(anchor).offset().top}, 'slow');
        }, 100);
    }

    $('a.scroll').click(function(e) {
        var trg = $(this).attr('data-target');
        if(trg != 'external') {
            e.preventDefault();
            var href = $(this).attr('href');
            $('html, body').animate({scrollTop: $(href).offset().top}, 'slow');
        }
    });
});

The link to an anchor on an external page will look like this:

<a href="inner.html#demo_2" class="scroll" data-target="external">DEMO 2</a>

Also, you can link to an anchor on the same page. In this case, you won't need to add any data-target. I wrote the script the way that is supports both:

<a href="#demo_3" class="scroll">Go TO DEMO 3</a>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!