Smooth scrolling feature malfunctioning in mobile view

While working on my website, I noticed that the smooth-scroll feature works perfectly on desktop browsers. However, on mobile devices, when I click on a link, it does not scroll to the correct position. It always ends up much lower than expected. Any idea why this might be happening?

I have carefully checked the code and documentation of Smooth Scroll, but everything seems to be in order.

Here is the link to my code: https://codepen.io/ZeR0ByTe/pen/wrbMRZ

<!DOCTYPE html>
<html lang="es">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport">
    <!-- Bootstrap CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/font-awesome.min.css" rel="stylesheet">
    ... (other stylesheet links)
    <script src="js/smooth-scroll.min.js"></script>
    <script src="js/wow.min.js"></script>
    ... (other script tags)
</head>
... (body content)
</html>

-(Apologies for any language errors)

-(Please note that the tablet layout is still a work in progress)

Thank you!

Answer №1

A kind friend was able to help me with my issue, so I'm sharing the solution here in case it might benefit someone else.

I decided to remove the JS library SmoothScroll and the associated code to initialize it.

// SmoothScroll
        var scroll = new SmoothScroll('a[href*="#"]', {
        speed: 2000, 
        offset: 0, 
        easing: 'easeInOutQuart', // Easing pattern to use
     });

Instead, I made the following replacement:

$('a[href*="#"]')
  .not('[href="#"]')
  .not('[href="#0"]')
  // Remove links that don't actually link to anything
  .click(function(event) {
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      && 
      location.hostname == this.hostname
    ) {
      // Determine element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Check if a scroll target exists
      if (target.length) {
        // Prevent default behavior only if there will be an animation
        event.preventDefault();

        var scrollTop = target.offset().top - $('.sticky-top').height();

        $('html, body').animate({
          scrollTop: scrollTop
        }, 1000)
      }
    }
});

The above code has been customized to suit my requirements, but it was originally inspired by: https://css-tricks.com/snippets/jquery/smooth-scrolling/

Thank you once again, and apologies for any language errors.

Answer №2

I found a solution to this issue by adjusting the offset value specifically for mobile window widths.

const options = {
    speed: 500,
    speedAsDuration: true,
    offset: window.innerWidth < 768 ? 400 : 90
}
new SmoothScroll('a[href*="#"]', options);

It appears that the problem lies in the fact that the library requires a higher offset value on mobile devices, possibly due to differing element dimensions compared to desktop.

I hope this information proves useful to you or someone else facing a similar challenge.

Best regards

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: Unable to locate element with the specified selector: #email

const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://discord.com/register'); await page.screenshot({path: 'b.png ...

Position the icon to the left side of the button using Bootstrap

Need help with centering text on a bootstrap 3 button while aligning the font awesome icon to the left side. <button type="button" class="btn btn-default btn-lg btn-block"> <i class="fa fa-home pull-left"></i> Home </button> Usi ...

Page refreshing in Angular 5 consistently redirects to the home page instead of staying on the current page

I am experiencing an issue with the navigation on my application. When I navigate to routes like getEmp-by-id or page-not-found and hit refresh, the application automatically redirects me back to app-home. However, I would like it to stay on the same pag ...

text field remaining populated

I have a form where the input fields clear when they are clicked on. It works well on most pages, but there is a specific type of page where it is not functioning properly due to the presence of another javascript running. - issue observed // On this pa ...

ReactJS component's function become operational only after double tapping

Dealing with the asynchronous nature of react hook updates can be a common challenge. While there are similar questions out there, I'm struggling to find a solution for my specific case. The issue arises when trying to add a new product object into a ...

Inconsistent reliability of Loopback-context prompts the search for an alternative solution

After encountering some reliability issues with the loopback-context package, I decided to try an alternative approach. Instead of relying on setting the current user object in my middleware using loopback-context, I opted to fetch the accessToken from the ...

What causes the disparity in functionality between CSS's Left 75% and Right 25% properties?

Here is my CSS code snippet: .bloodparam > .highvalue { bottom: 12px; right: 25%; } and .bloodparam > .highvalue { bottom: 12px; left: 75%; } I expected the element to be in the same position with both lines of code, but I'm noticing differe ...

Modify the state of each individual button

I recently came across a cool implementation using clicks and jQuery fade effects to show a div when a button is clicked and then change the state of the button. Check it out here: http://jsfiddle.net/ttj9J/5/ HTML <a class="link" href="#" data-rel="c ...

Express.js and Node version 0.10.29: The Mystery Post

Having trouble with sending JSON data to an express server and receiving 'undefined' for req.body.name. This is how the configuration is set up: const express = require('express'); const app = express(); app.configure(function(){ ...

Is there a way to give only the left corners of a button a rounded look?

Here is the visual representation of the button: https://i.stack.imgur.com/Bjlkp.png ...

I encountered an AJAX error while working on my project

Encountering an error with my login_process.php when using ajax, preventing me from progressing. All files are stored in a single folder. Upon running the HTML log-in page, the error becomes visible. Below is the code snippet, quite straightforward. Previo ...

Launching an image link within the same location on the subsequent page to which it is directed

I'm completely new to creating websites so I may not be using the correct terminology. I've searched with various terms and ideas but haven't found any solutions to help me ask my question effectively or find examples of what I'm lookin ...

Issue: The variable 'HelloWorld' has been declared but not utilized

Why am I encountering an error when using TypeScript, Composition API, and Pug templating together in Vue 3? How do I resolve this issue when importing a component with the Composition API and using it in a Pug template? ...

Exploring the world of promise testing with Jasmine Node for Javascript

I am exploring promises testing with jasmine node. Despite my test running, it indicates that there are no assertions. I have included my code below - can anyone spot the issue? The 'then' part of the code is functioning correctly, as evidenced b ...

What is the best way to verify the existence of a remote image in AngularJS?

Here is an example of the code snippet : <div ng-repeat="u in users"> <!--An active URL will always be received --> <div ng-if="u.imageUrl"> <!--Check if the provided URL is active--> <!--Content only visible if image url is li ...

Configure unique headers for various environments

I am looking to customize headers like "id", "env", and "name" based on different environments in my application. Each environment has a unique set of values for these headers. I am struggling to implement this effectively within my existing code logic. T ...

Can data be transferred from one website to another without the use of an API?

I am a newcomer to the world of web development with basic knowledge of JS, Node, Express, Mongoose, and MongoDB. I have an exciting idea for a web application that would function like a spreadsheet, gathering user inputs to generate an output. The unique ...

Setting up a specific print media query for the body element through JavaScript

I'm facing an issue with my web page that has a bootstrap modal which pops up when a button is clicked. I've added a print media query to print the content of the modal, but it's causing a problem. When I include the media query in the CSS, ...

HTML - Centered layout with a constant header and footer

Imagine a layout where there is always a header at the top, a footer at the bottom, and the space between them should be filled by the content 100% (image 2). Additionally, everything in the header, content, and footer should be horizontally centered, usin ...

Error message: The function pokemon.map does not exist

I'm new to learning react and I've been working on creating a react app using the pokemon API. However, I've encountered an error that says TypeError: pokemon.map is not a function. I'm unsure why .map is not recognized as a function in ...