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

Setting a false condition on jQuery's .on('canplaythrough') event

Struggling to implement a custom audio control with jQuery, but encountering some issues. I'm in the process of converting native JavaScript to jQuery for consistency in my code, however, I can't seem to get it working. The original code that is ...

The significance of documenting and optimizing code execution

My coding practice is to always (or at least try to) add comments to my code. However, I have set up my server to delete those comments and extra white space before the final delivery. Should I omit comments from the live system's code (Javascript/php ...

Revamp your arrays with input fields in Vue3

When presented with two arrays of options, users must select an option from each array. ==> first array: [ orange, green, yellow ] ==> second array: [ orange, green, yellow ] The challenge is to update the second array based on the user's sele ...

Using CodeIgniter framework for processing form submissions asynchronously using AJAX

I'm currently facing a challenge where I need to save data submitted from a form to my mysql database, and then update the div element with the latest posted item at the beginning of the list in the div. At this point, my main focus is on receiving a ...

Unable to maintain sequential IDs for textboxes using Javascript or JQuery

I am encountering a problem involving the addition and deletion of multiple text boxes using buttons. The issue lies in maintaining sequential IDs for each textbox. Below is an explanation of my code: <div class="form-group" id="intro-box"> < ...

Customizing the DatePicker with a unique button in material-ui

For my current project, I am utilizing a Datepicker component. I am looking to incorporate a custom information button in the upper right corner of the calendar layout, similar to the example image provided below: https://i.stack.imgur.com/fHMbn.png Unfo ...

Issues with Node AssertionErrors cause failures to be silent and prevent proper error output

I am facing an issue with a particular method in my code. The code snippet is as follows: console.log('Trouble spot here') assert(false) console.log('Will this show up?') Upon running this code within my application, the followi ...

I am facing difficulty in retrieving a unique dynamic div id using the useRef ReactJS hook, as it keeps returning the same id repeatedly

When using the useRef Reactjs hook, I encountered an issue where it returned the same id repeatedly instead of generating a dynamic div id. I need this functionality to map buttons and div ids in order to create a flexible accordion. The goal is to displ ...

Improving HTML coding with a more effective alternative to document.write()

Looking at the setup of my website, I have a menu button and comments section that need to appear on every page. Instead of manually adding this code to each HTML file, I decided to streamline the process by using a JavaScript file that generates all of th ...

exploring the contrast of css versus javascript selectors

Could you please explain the contrast between div#name and #name? Is there a significant difference when using class or id to position an element? Thank you for your help. ...

Decrease initial loading time for Ionic 3

I have encountered an issue with my Ionic 3 Android application where the startup time is longer than desired, around 4-5 seconds. While this may not be excessive, some users have raised concerns about it. I am confident that there are ways to improve the ...

Migrating WordPress Gutenberg to a Separate React Component: Troubleshooting Missing CSS Styles

I am in the process of developing a standalone version of the Gutenberg block editor from Wordpress that can function independently outside of the Wordpress environment. My goal is to integrate the Gutenberg editor as a React component within an existing R ...

Concealing the text input cursor (caret) from peeking through overlaid elements on Internet Explorer

Currently, I am facing an issue with a form that includes a unique widget. This particular widget automatically populates a text input when it is in focus. The problem arises when the widget appears above the text input as intended. In Internet Explorer ...

Tips for executing a function in the HC-Sticky plugin?

Currently, I am utilizing the HC-Sticky JavaScript plugin and endeavoring to utilize the documented reinit method. However, I am facing difficulty in understanding how to execute it. In this CodePen demo, a basic setup is displayed along with an attempt t ...

The background fade effect is not fully displaying in Internet Explorer

My code is designed to create a fade effect on the background while displaying a popup. Here is the div container: This is the CSS used for the same: #VbackgroundPopup{ display:none; position:fixed; _position:absolute; /* hack for internet explorer 6*/ t ...

`Trick Ajax into displaying 200 status code even on error responses`

Is it possible to suppress exceptions in the console by manually setting the status code to 200 for all errors? For example, can I change a 500 internal server error response to 200? Although I understand that hard-coding status codes is generally conside ...

Undefined is the value assigned to Javascript Dot Notation

When using dot notation to access objects with a '.', I am encountering an issue that I cannot seem to figure out. The success function in my jQuery $.ajax function looks like this: success: function(data){ console.log('data = ' + da ...

Building Your Own Array Object in JavaScript

Yes, it may seem crazy at first glance, but let me clarify things a bit. When using Jquery, for instance $('div'), it returns an Array Collection similar to this: [div#container, div#header, div#logo]. The interesting part is that primitive Arra ...

Implementing Vue.js functionality to dynamically add or remove values from an array based on the state of a checkbox

I recently embarked on my journey to learn vue.js and I've encountered a challenging issue. I have dynamic data that I render using a 'v-for' loop. Additionally, I have an empty array where I need to store checked checkbox data and remove it ...

Running an Angular-made Chrome extension within an iframe: A guide

I'm currently working on creating a Chrome extension that displays its content in a sidebar rather than the default popup. I've come to realize that in order to achieve this, I need to use an iframe due to the limitations of the default chrome ex ...