Unexpected behavior observed when trying to smoothly scroll to internal links within a div, indicating a potential problem related to CSS dimensions and

Within a series of nested div containers, I have one with the CSS property overflow:hidden. My goal is to smoothly scroll to internal links within this specific div using jQuery. The snippet of code below has worked successfully in previous projects:

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('#cardb').animate({
                scrollTop: target.offset(
                ).top
        }, 0500);
        return false;
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="slide4" class="slide">
  <div id="carda">
    <p>CARD A</p>
  </div>
          <div id="cardb">
                <div id="cardb-1">
                    <p>CARD B 1</p>
                </div>
                <div id="cardb-2">
                    <p>CARD B 2</p>
                </div>
                <div id="cardb-3">
                    <p>CARD B 3</p>
                </div>
                <div id="cardb-4">
                    <p>CARD B 4</p>
                </div>
              
              <div id="linkcontainer">
                  <a href="#cardb-1"><div class="linkcircle"></div></a>
                  <a href="#cardb-2"><div class="linkcircle"></div></a>
                  <a href="#cardb-3"><div class="linkcircle"></div></a>
                  <a href="#cardb-4"><div class="linkcircle"></div></a>
              </div>
  </div>
</div>

I'm facing unexpected results where the links do not consistently scroll to the correct target, and clicking on the same link twice still triggers scrolling (e.g. when at #cardb-1 and clicking its link again, the div scrolls elsewhere). Even after researching extensively as a newcomer to jQuery, I've seen no improvement. It's possible that the issue lies in my CSS implementation, but I can't pinpoint where I may have made an error. When I disable the jQuery, the links appear correctly at their expected positions.

Answer ā„–1

I have encountered the same issue and found your code to be a helpful starting point, so thank you.

To prevent the scrolling from occurring again when clicking on the same link, I added the following code at the beginning of the function:

if( location.hash == this.hash){ return false;}

However, there seems to be a delay of 1 or 2 seconds for the new hash to take effect. During this time frame, if you click on the same link twice, the problem persists. After this delay, no further scrolling occurs. I am currently exploring ways to eliminate this 1-2 second refresh delay, but it's progress nonetheless.

Answer ā„–2

Below is a piece of code that effectively scrolls to the designated location on the webpage. The key lies in using the animated function with an absolute y value, as opposed to just accounting for the top position which excludes margins. Additionally, there seems to be an extra 100px added (in my specific case) and its origin is unclear to me. Therefore, I loop through all div elements until I find the target one, calculating its precise position along the way. This approach also resolves any issues when rapidly clicking on multiple links.

     $(function() {
        $('a[href^="#"]').click(function() {
            if( location.hash == this.hash){ return false;}
            var target = $(this.hash);

            var targetId = this.hash.substr(1);
            var toGo = 0;

            // loop through each div containing an anchor link id
            $('.info-box').each(function() {
                var box = $(this);

                if( this.id == targetId){
                    toGo += box.outerHeight(true)-box.outerHeight();
                    return false;
                }
                toGo += box.outerHeight(true)-box.outerHeight();
                toGo += box.outerHeight();
            });

            if (target.length) {
                // scroll animation targeting the container div's id  
                $('#page').animate({scrollTop: toGo}, 700);
                return false;
            }
        });
     });

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

Remove the float from the final list item in order to resolve display issues in Internet Explorer

I am trying to create a menu with the following HTML structure: <ul> <li id="btnHome"><a href="#">Link One</a></li> <li id="btnAbout"><a href="#">Link Two</a></li> <li id="btnContact"> ...

Enhancing code branch coverage using Istanbul

The code snippet provided has a branch coverage of only 50% (refer to the coverage report below). I am unsure how to enhance this as there are no if statements present. I suspect that Istanbul must utilize some form of measurement that I have yet to grasp ...

Is there a way to avoid waiting for both observables to arrive and utilize the data from just one observable within the switchmap function?

The code snippet provided below aims to immediately render the student list without waiting for the second observable. However, once the second observable is received, it should verify that the student is not enrolled in all courses before enabling the but ...

Learn the process of sending code to a database using AJAX

I am facing a challenge in saving HTML and Javascript codes to a Database using Ajax. I am unsure about the optimal way to do this. Writing all the codes as Strings for the variable seems cumbersome. Do you have any suggestions to simplify this process? & ...

Using the clip-path property to determine the content padding within a div

I am encountering an obstacle while attempting to insert icons into a polygon-shaped div. The problem lies with the padding, as the icons get cut off by the borders of the polygon. #container { width: 200px; height: 200px; border: 2px solid blac ...

Tips for using various versions of jQuery at the same time

Despite searching on Stack Overflow, none of the answers provided seem to work for my issue. My requirement is to utilize two separate versions of jQuery. Below is the code snippet: I first link to the initial version and use the following code: <sc ...

Sending data from MongoDB API to HTML in Electron using parameters

I am currently developing an Electron application for my personal use and utilizing MongoDB Atlas as the backend for my Node application. As I am relatively new to Electron, I am still experimenting with different approaches, so there might be some minor m ...

Challenges encountered while creating a Number Tables Program (such as displaying 12 x 1 = 12) using Javascript

Currently, I am working on developing a program that can generate mathematical tables for any given number. For example: 3 x 1 = 3 3 x 2 = 6 3 x 3 = 9 3 x 4 = 12 To achieve this, the user should provide the following inputs: (1) The number they want ...

The EJS template in an Express.js (Node.js) application is not updating to show recent modifications

I'm currently developing a node.js application that serves an index.ejs page through a route named index.js. var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) ...

Is it possible to forecast an on click event using jQuery?

I have encountered a specific issue. Within my code, there are certain elements, specifically <li> elements, that undergo a particular operation triggered by a click event: $('.panelTabs li').on('click', function () { // ..som ...

I'm attempting to access a PHP file by clicking a button using AJAX and jQuery

I am just starting to learn the basics of jQuery and AJAX. I have already attempted to solve this problem by checking previous answers on Stackoverflow, but the code provided did not work for me. I have created two pages, index.php and testing.php, with a ...

The customer opts to store all images indefinitely into the data stream

I have set up a node server that captures images from a webcam at regular intervals and sends them to the client using the Delivery.js node module. Upon monitoring the browser resources in Chrome development tools, it appears that each image sent is being ...

Type of JavaScript map object

While exploring TypeScript Corday, I came across the following declaration: books : { [isbn:string]:Book}={}; My interpretation is that this could be defining a map (or dictionary) data type that stores key-value pairs of an ISBN number and its correspon ...

When I clicked on the event in Javascript, the result was not what I expected

I am currently working on a web project centered around cooking recipes. In order for users to add ingredients to their recipes, they must input them one by one into a dynamic list that I am attempting to code using jQuery (AJAX). My issue arises when a u ...

Refresh a div using jQuery and include PHP files for dynamic content updating

This is the code I am using to dynamically update divs containing PHP files: $(document).ready(function() { setInterval(function() { $('#ContentLeft').load('live_stats1.php').fadeIn("slow"); $('#ContentRight').load( ...

Is it possible to synchronize functions in node.js with postgresql?

Iā€™m facing some challenges in managing asynchronous functions. Here is the code snippet that's causing the issue: var query = client.query("select * from usuario"); query.on('row', function(user) { var queryInterest = client. ...

DiscordJS bot using Typescript experiences audio playback issues that halt after a short period of time

I am currently experiencing difficulties with playing audio through a discord bot that I created. The bot is designed to download a song from YouTube using ytdl-core and then play it, but for some reason, the song stops after a few seconds of playing. Bel ...

Tips for creating a form with recurring elements efficiently

Currently struggling to summarize the issue at hand with a simple title, so here's the detailed explanation: Imagine I'm inputting information for multiple contacts, and there are various fields involved: Name of the contact Method of Contact ...

The AJAX XMLHttpRequest has encountered an issue while trying to load the specified <url>, as it received an invalid HTTP status code

UPDATE/FIXED Thank you to everyone for your answers. I finally discovered the solution! (explained in a simple way) The issue was with connecting to a remote node server URL/page. After gaining access to the node server, I found code in a file named app.j ...

What's the best way to incorporate necessary styles into text using particular fonts?

Is there a way to set letter spacing and word spacing for text on my website with the font 'classylight'? Adding classes to each post in the site map seems like a lengthy process. To save time, I attempted to use the attribute*=style property to ...