Randomly browsing with two clicks in jQuery

Attempting to achieve smooth scrolling on div tags by clicking anchor tags in a list using jQuery.

enter code here
        function scrollThere(targetElement, speed) {
       // initiate an animation to a certain page element:
      $('html, body , #side').stop().animate(
      { scrollTop: targetElement.offset().top }, // move window so target 
      element is at top of window
      speed, // speed in milliseconds
     'swing' // easing
      ); // end animate
    } // end scrollThere function definition


     //--- START NAV-ITEM CLICK EVENTS ---//
    // when the user clicks a nav item:
    $("#leftSidebar ul li a").click(function (e) {

    e.preventDefault(); // don't jump like a typical html anchor

    // find the index of the "#" character in the href string...
    var startOfName = $(this).attr('href').indexOf("#"),
    // ...then use it as the argument in the slice() method (add 1 so you 
    don't include the # character).
    clickRef = $(this).attr('href').slice(startOfName + 1),
     targetEl = $('a[name=' + clickRef + ']'); // select the element this 
     link is pointing to

    // scroll there smoothly:
    scrollThere(targetEl, 400);

    });

Encountering an issue where clicking on a link twice results in being taken to the top of the page and causing issues with scrolling. The scrolling behavior seems inconsistent as the size of the div tags increases. A demonstration of the problem can be found in this fiddle https://jsfiddle.net/60tp46y3/18/. Ideally, clicking on specific links on the left should smoothly scroll the right section to the corresponding id.

Answer №1

I just made some adjustments to your code and now it's functioning correctly.

https://jsfiddle.net/t0of2kzp/

The issue was that you were not taking into account the current scroll position of the container that holds all the other elements.

// targetElement refers to the surrounding div of the target link.
var postionOfTargetElement = targetElement.offset().top;
// This is the main container
var scrollPosition = targetElement.parent().scrollTop();
// Here we calculate the actual top position by considering the scroll position of the main container.
var topTarget = postionOfTargetElement + scrollPosition;

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

The behavior of CSS position: sticky varies depending on whether the user is scrolling up or scrolling down

I am experiencing an issue in my Vue CLI app where a component with the position: sticky CSS property is being partially hidden under the top of the browser when scrolling down, but works correctly when scrolling up. This behavior is also observed on my Ga ...

Make desktop view the default even when accessing from a mobile device

I have searched through all other similar questions but have not been able to find a solution. I am new to programming and am currently learning CSS. I have created a webpage with the following code: <html> <style> body { p.Welcome { ...

What is the best way to instantiate objects, arrays, and object-arrays in an Angular service class?

How can I nest an object within another object and then include it in an array of objects inside an Angular service class? I need to enable two-way binding in my form, so I must pass a variable from the service class to the HTML template. trainer.service. ...

What is the process for transforming JSON into a different format?

Currently, I have a JSON array structured as follows: var data = { report: [ { Name: "Nitin", comment: [ { count: 0, mName: "Feb" }, ...

What is the best way to adjust the CSS height of an HTML select element to 100% within a table cell in Internet Explorer

Is it possible to make a select (dropdown list) element fill out 100% of the table cell height? I was successful in getting it to work in Firefox and Chrome, but unfortunately not in IE (Internet Explorer). Here is the test HTML code: <table> & ...

What is the most efficient approach for handling numerous transactions individually through AJAX calls?

Just a heads up: there's quite a bit of pseudo code coming up, but it's necessary to illustrate my issue. My solution involves more complex management of ajax icons and statuses, but I've simplified it for clarity. Essentially, I'm fac ...

Issues with the functionality of the ZeroClipboard Angular plugin

"> I'm fairly new to Angular and currently experimenting with a module called ZeroClipboard. I've made adjustments to my application in order to incorporate the module and configured it as per the demonstration. var app = angular.module ...

Incorporating JavaScript/jQuery values into C# backend with ASP.NET

Despite attempting all possible methods, I am unable to pass the screen.width value from a JS script on an aspx page to C# in the code behind. Even though the screen.width is correctly assigned, it never gets passed to my hidden field value. <asp:Conte ...

In the XHTML mode, MathOverflow's invaluable mathematical expertise shines brightly

I am interested in incorporating the unique “piece of valuable flair™” from MathOverflow onto my website. The issue I am facing is that I want my webpage to comply with XHTML5 standards, meaning it should be served with the MIME type application/xht ...

What is the more effective option: utilizing the bootstrap offset feature or inserting an empty div?

<div class="col-xs-3"></div> <div class="col-xs-6 col-sm-6 col-md-6" style="min-width: 320px;"> </div> OR <div class="col-xs-6 col-md-offset-3 col-sm-offset-3 " style="min-width: 320px;">` </div> I would like to remo ...

Transform geojson data into an HTML table

As someone new to JavaScript, I am trying to figure out how to populate a HTML table with geojson entries like "ename" etc. Here is my current code: <table id="jsoncontent"></table> <script type="text/javascript"> window.onload = fu ...

Extracting data from a jQuery function

When I try to call the method getSelectedIndex from the plugin Megalist, like so: var selectedIndex = $('#left-list').megalist('getSelectedIndex'); I'm not getting an integer as expected, but rather a jQuery object representing t ...

Ensuring the authenticity of dynamic forms

jQuery(document).ready(function(){ $("#submitButton").click(function () { if ( $("#formToSubmit").validationEngine('validate') == true) { $("#formToSubmit").submit(); } }); Utilizing the Validation Engine plugin for jQuery to valida ...

Retrieving Text following an HTML Element with a Parsing Tool

I'm currently utilizing PHP Simple HTML DOM for the development of a web scraper application. Here is the HTML structure from which we need to extract the City/State name, such as "Daviston, AL" in the example below. Can anyone assist me wi ...

Aligning rotated text in a bootstrap 4 table header

In my Bootstrap 4 project, I'm having difficulties with positioning rotated text within a table header. My goal is to align all the rotated text at the bottom of the cell and centered horizontally. Despite trying different transform-origins, it seems ...

Ways to both retrieve a variable and clear it simultaneously

In my validator library, there are functions that sanitize and validate strings. These validator functions add error messages to an array called "errors" for each invalid input they encounter. After completing validation on all inputs, I collect the error ...

What is the best way to trigger an action in response to changes in state within Vuex

Are there more sophisticated methods to trigger actions in vuex when a state changes, rather than using a watcher on that state? I want to ensure the most efficient approach is being utilized. ...

Angular.js is failing to display content

<html ng-app = "sampleMod"> <head> </head> <body ng-controller = "sampleCon"> <script src = "bower_components/angular/angular.min.js"></script> <h1>Filters example</h1> C ...

Looking for assistance with increasing the output size in JavaScript

As a beginner in JavaScript, I managed to create a form with a textarea and a button to display the text from the textarea in a div tag. Additionally, I added two buttons that are meant to increase the size of the text in the div tag when clicked, as wel ...

Create a unique onblur event listener for every element in a loop in Javascript

https://i.sstatic.net/tRYul.png I have added several items to a column in the database, but I am unsure of how to implement an onblur function for validation for each item within a loop. For example, if the NAME field is empty, I want to display an alert ...