Front-End & Daily

[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

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.

Comments

After reviewing the content, we will publish it, omitting any personal information.

Enter your name and email address

Please enter if you would like a reply via email.

The personal information provided will not be disclosed. It will only be used for replies.

It will be sent directly. Please confirm and click "Send".

If this was helpful, we appreciate your support!
Any support received will be used for childcare.

Support with OFUSE


Or support by buying something from the buttons below
(You don't have to buy the linked product.)

Amazon

Rakuten Ichiba

Yahoo! Shopping

PR

As an Amazon Associate, "けん" earns income from qualifying purchases.

Share

Share on Twitter Share on Facebook Share on LINE Share on Hatena Bookmark