开发者

jQuery - How to scroll the page to a div if div dynamically moves?

开发者 https://www.devze.com 2023-03-28 06:38 出处:网络
Currently I am creating a website mainly using a mix of PHP, SQL, and JS. I use the JS to dynamically pull up new data using PHP and SQL. The current issue I am running into is that I have a button th

Currently I am creating a website mainly using a mix of PHP, SQL, and JS. I use the JS to dynamically pull up new data using PHP and SQL. The current issue I am running into is that I have a button that when clicked 开发者_运维百科will have the page scroll to the current DIV every 2.5 seconds based on offset. The issue is the function does not find the NEW offset once the element has moved.

Code snippets:

...

$(".button").click(function() {
            $message_focus = "TRUE";
            $to_focus=($(".focus_on_this").offset().top);
        });

...

if ($message_focus = "TRUE") {
        $("html, body" ).animate( { scrollTop: ($to_focus) },{ queue:false, duration:750 } );
    }

...

That is where the main issue is. It all works fine, though it only goes to the initial div's starting location. Thank you in advance for your response.


You have to recalculate .focus_on_this's position everytime you scroll the page:

var $message_focus = false;

$(".button").click(function() {
    $message_focus = true;
});

setInterval(function() {
    if ($message_focus == true) {
        $("html, body" ).animate({
            scrollTop: $(".focus_on_this").offset().top
        },{
            queue:false,
            duration:750
        });
    }
}, 2500);


How does the div dynamically moves? Is there any event which causes it to move? If yes then we need to set $to_focus=($(".focus_on_this").offset().top); every time this event is triggered. Only setting it on click will not work.

In the question you have mentioned on button click the page scrolls to the div every 2.5 seconds but I dont see any such code. You should use setInterval if you want to call any code repititively after a certain period as below.

setInterval(function(){
   //Do something after every 2000 milliseconds

}, 2000);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号