简体   繁体   中英

jquery linking to div id after page load - but page continues to load after animate

The overall goal of this task is to animate scroll the user to a certain div lower down on the page, depending on whatever #hashName is appended to url.

The html I am working with does not have the correct div id added, so I am adding that via javascript on document ready. Once the div id is added, then I have script that determines the hash passed in, then pass the user to the hash. This following code works:

jQuery(document).ready(function($){
    //append new div id to current FAQ class
    document.querySelector('.press-24_tab').id = 'faq';

    //now that we have correct div id, animate user to this div
       var target = window.location.hash;

       $('html, body').animate({scrollTop: $(window.location.hash).offset().top}, 'slow', function() {
            //in animate callback, attempt to keep user focused here
            $('#faq').focus();
        });
});

I am calling jQuery etc in the code so I can use this in WordPress.

This code works fine. My problem is, this script fires while the page is loading. And the page keeps loading. And as a result, the page focus goes back to the top of the page!

I was thinking of wrapping the animate to hash code inside $(window).on('load', function(){}); but this does not seem to work. Note my existing animate callback trying to keep user focused - but this is not sticking. Page still loads. Page takes a loooooooong time to load, so I am fighting against this.

So at this point I have hit a brick wall. I am reaching out to those smarter than me in javascript and jQuery to see what I have to do here. Any help would be greatly appreciated.

jquery(document).ready() will fire as soon as the DOM is ready so this is actually working as expected by the looks of things as the DOM isn't the same thing as the document itself.

If you need to wait for external content like web-fonts, images, videos etc you should use the window.load() event

jquery(window).load(function() {
  //append new div id to current FAQ class
  document.querySelector('.press-24_tab').id = 'faq';

  //now that we have correct div id, animate user to this div
  var target = window.location.hash;

  $('html, body').animate({
    scrollTop: $(window.location.hash).offset().top
  }, 'slow', function() {
    //in animate callback, attempt to keep user focused here
    $('#faq').focus();
  });
});

Have a look through the documentation for DOM here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM