[jQuery] Causes and fixes for when the smooth scroll position is off only the first time
![[jQuery] Causes and fixes for when the smooth scroll position is off only the first time](img/ogp.png)
I've encountered an issue where jQuery smooth scroll, which animates in-page links, has an incorrect position only the first time the page is opened.
This was caused by LazyLoad.
Table of Contents
Method ① Rewrite the JS
Let's replace the JS smooth scroll code with a LazyLoad compatible version.
$('a[href^=#]').click(function(e) {
var href = $(this).attr("href");
var target = $(href == "#" || href == "" ? 'html' : href);
var position = target.offset().top - headerHight;
$.when(
$("html, body").animate({
scrollTop: position
}, 400, "swing"),
e.preventDefault(),
).done(function() {
var diff = target.offset().top - headerHight;
if (diff === position) {
} else {
$("html, body").animate({
scrollTop: diff
}, 10, "swing");
}
});
});
Reference : https://teratail.com/questions/274473
If this is not possible, try the following.
Method ② Add width and height attributes to img tags
If Method ① is not possible, add width and height attributes to the img tags where LazyLoad is configured.
Like this:
<img data-src="img.jpg" width="100" height="100" class="lazyload">
This way, the height will be calculated even before the image is loaded, which should prevent position discrepancies.




If this was helpful, we appreciate your support!
Any support received will be used for childcare.
Or support by buying something from the buttons below
(You don't have to buy the linked product.)
Amazon
Rakuten Ichiba
Yahoo! Shopping
PR