Having trouble getting smooth scrolling with easing to function properly

I'm facing an issue with a JQuery function that is supposed to enable smooth scrolling using JQuery easing, but for some reason, it's not functioning correctly and I'm unable to pinpoint the error.

Here is the code for the function:

$(function(){
    $('a[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) {
                var targetOffset = $target.offset().top;
                $(‘html,body’).animate({scrollTop: targetOffset}, {duration:1600,easing:'easeInBounce'});
                return false;
            }
        }
    });
});

I created a demonstration of this function on JSFiddle. (I also included the code for the JQuery easing)

Additionally, here's a similar function on JSFiddle. Although this one works, it lacks the option to use easing. Any assistance in resolving this issue would be greatly appreciated.

Edit

To further elaborate on the problem, when the links are clicked, there is no animation - it simply jumps instantly to that section of the page.

Answer №1

You have some pretty strange things happening here.

In the line below, there seems to be a mix-up with single double-quotes instead of two single quotes:

if (location.pathname.replace(/^\//,”) == this.pathname.replace(/^\//,”) && location.hostname == this.hostname) {

Also, on this line, non-single quote characters are being used:

$(‘html,body’).animate()

As a result, we end up with this. jsFiddle

$(function(){
    $('a[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) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({scrollTop: targetOffset}, {duration:1600,easing:'easeInBounce'});
                return false;
            }
        }
    });
});

UPDATE

In response to the questions in the comments for this answer, to make the "#" link work correctly, you should adjust the $target = line like this:

$target = $target.length ? $target : $('html');

To display the anchor on the page, simply remove the return false; from the function. After tweaking the code, it has been condensed to this:

$(function () {
     $('a[href*="#"]').click(function () {
        var $target = $(this.hash);
        $target = $target.length ? $target : $('html');
        var targetOffset = $target.offset().top;
        $('html,body').animate({scrollTop: targetOffset}, {duration: 1600, easing: 'easeInBounce'});
     });
});

Answer №2

Encountering an issue where the solution above causes a jerky movement when clicking on a link before smoothly scrolling down. For those facing the same problem, try using this updated version as it provides a smoother experience.

    // Utilizing jQuery easing for smooth scrolling with various links
    $('a[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) {
                $('html, body').animate({
                    scrollTop: (target.offset().top - 54)
                }, 1000, "easeInOutExpo");
                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

Updating a component from a different source

As a newcomer to React, I'm curious about the ability to update one component's content based on events from another component. I have two React components set up. The first component loads data when the page initializes, while the second compon ...

PHP cannot be utilized within the script tag

I'm currently using JavaScript to display an error message If a user inputs incorrect information and I add the following code: <?php $_POST["usernamereg"] ?> = usernamereg; the alert function stops working. However, if I remove this code, t ...

Tips for Removing Copyright on Charts

Check this out : https://jsfiddle.net/oscar11/4qdan7k7/5/ Is there a way to eliminate the phrase JS chart by amCharts? ...

What is the reason behind ValidatorValidate() validating all RequiredFieldValidator controls on the page?

Can you explain why the function ValidatorValidate(v) validates all the RequiredFieldValidator controls on the page instead of just executing for RequiredFieldValidator1? Here is the code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> ...

I'm getting a JS error saying that the variable "var" is not defined. Does anyone know how I can

Here is the code I am using to dynamically create a sitemap.xml file when accessing /sitemap.xml database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ ...

Altering Hues with a Click

One thing I wanted to achieve was changing the color of a hyperlink once it's clicked. I managed to make it work by using the code below: var current = "home"; function home() { current = "home"; update2(); } function comp() { current ...

Is there a way to adjust the font color when the expiration date passes?

My goal is to change the color of text to green when the expiration date has not been reached yet. If the expiration date has passed, then the text should be red. .curentDate { color: rgb(54, 168, 54) } .expirationDate{ color: red; } <div cl ...

Performing ad-hoc queries on a Postgresql database using Node.js and Express to manipulate row data

I am faced with a challenge of selecting one entry randomly from a table containing 46 entries, and then passing the data from that particular query to my handlebars files. I am unsure about how to approach the task of randomly querying the database and re ...

Design an HTML button/label with text and a starting width of zero

I'm attempting to design HTML buttons and labels with text that initially have zero width. Once inserted, they should smoothly transition to a visible state. I've tried adjusting the initial width and min-width style properties without success. ...

Showing NaN/NaN when no results were found in jQuery DataTables

I found a jQuery data tables function on Stack Overflow that I am using. Here is the code: var oTable = $('#test').dataTable( { "aoColumnDefs": [ { "bSortable": false, "aTargets": [ 0 ] } ], "aaSorting": [[1, 'asc'] ...

Unleash the power of jQuery to leverage two different input methods

Here is the code I'm working with: $('input[type="text"]').each(function(indx){ Right now, this code targets input elements with type "text". But how can I modify it to target both inputs with type "text" and "password"? Any suggestions o ...

How to pass extra value in IE7 and IE8 when selecting an option from a 'select' form

When passing expiry parameters using a form 'select' option, everything seems to be working fine in most browsers except for IE7 and IE8. Upon inspecting the form snippet and the array received from the card processor logs, it was noticed that an ...

Create a visual representation using a push button

Hey there, I'm attempting to create an image using a button on canvas. However, I'm facing an issue where I can't draw on the clear canvas. Here's my code: <!doctype html> <html> <head> <meta charset="utf-8"> ...

The HTML element cannot be set within page.evaluate in Node.js Puppeteer

I've run into an issue while using node.js puppeteer, specifically with the page.evaluate method. I'm experiencing difficulties with this part of my code: console.log(response); //This line is valid as it prints a regular string awa ...

Using Express-session in the Internet Explorer browser

When configuring the express-session plugin, I follow this setup: var express = require('express'), session = require('express-session'), uuid = require('node-uuid'); var expiration_day = new Date('9/15/2015&apo ...

Tips for customizing MUI PaperProps using styled components

I am trying to customize the width of the menu using styled components in MUI. Initially, I attempted the following: const StyledMenu = styled(Menu)` && { width: 100%; } `; However, this did not have any effect. After further research, I ...

Is there a way to integrate AJAX response Successful JSON data into a jQuery Datatable?

I am attempting to incorporate JSON data into a Datatable that I receive from an AJAX post Response. However, my current process is not functioning properly. Can anyone provide any suggestions or tips? Here is my AJAX code: $.ajax({ method: "POST", ...

Trouble with AJAX request on iPad, works perfectly on desktop

Here is some of my custom plugin code (function ($) { $.fn.createGallery = function(options) { var theObject = $(this); var settings = $.extend({ // Default settings. server: 'http://localhost/jQuery%20Gall ...

Intensive analysis of objects comparing their characteristics

Currently delving into the world of Javascript, I encountered a coding exercise involving a "deepEqual" function that I attempted to write but ultimately struggled with. Even after reviewing the solution, one particular part perplexed me - the for loop, ...

How should a JavaScript object be properly formatted?

Recently, I created a project using ng-repeat with AngularJS 1.x, and it was smooth sailing. JavaScript: var app = angular.module('myModule', []); app.controller('myController', function() { this.dishes = [ { 'name&a ...