Fade in animation when scrolling

I have developed a simple link animation for scrolling. This link can be used to navigate to a section within the same page or an external URL. However, there are a couple of issues that I encountered with this implementation.


First Issue: When clicking on the button ("section 4"), there is a strange movement experienced. This inconsistency was the initial problem I faced.
Second Problem: If a user clicks on a button multiple times and then proceeds to click on another button, the scroll function does not work until the previous click action has completed:
The code snippet is as follows:

 $(".links a").click(function () {
            $("html, body").animate({
                scrollTop: $($(this).attr("href")).offset().top
            }, 1400)
        })
.links {
    width:600px;
    position:fixed;
    top:0;
    padding:20px;
}
.links a {
    display:inline-block;
    padding:10px 20px;
    border:1px solid #0094ff;
}
.section {
    width:400px;
    height:200px;
    margin:300px auto 600px;
    background-color:#0094ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="links">
        <a href="#section1">Section 1</a>
        <a href="#section2">Section 2</a>
        <a href="#section3">Section 3</a>
        <a href="#section4">Section 4</a>
        <a href="http://google.com">External Link</a>
    </div>
    <div id="section1" class="section"></div>
    <div id="section2" class="section"></div>
    <div id="section3" class="section"></div>
    <div id="section4" class="section"></div>

Note: Please refrain from suggesting any plugins, as I am keen on exploring Javascript further.

Answer №1

If you want to prevent the default event behavior, you can use e.preventDefault().

To pass the event argument into the click event, make sure to include it in your function like this:

$(".links a").click(function (e) {

With this setup, you are now able to control the default event of the click using preventDefault. More details on https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault.

In addition, you can utilize stop() to correct any animation issues.

 $(".links a").click(function (e) {
  if ($(this).attr("href").charAt(0) == "#") {
    e.preventDefault();
    $("html, body").stop().animate({
      scrollTop: $($(this).attr("href")).offset().top
    }, 1400)
  }
});
.links{
                width:600px;
                position:fixed;
                top:0;
                padding:20px;
            }
            .links a{
                display:inline-block;
                padding:10px 20px;
                border:1px solid #0094ff;
            }
            .section{
                width:400px;
                height:200px;
                margin:300px auto 600px;
                background-color:#0094ff;
            }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="links">
        <a href="#section1">Section 1</a>
        <a href="#section2">Section 2</a>
        <a href="#section3">Section 3</a>
        <a href="#section4">Section 4</a>
        <a href="http://google.com">External Link</a>
    </div>
    <div id="section1" class="section"></div>
    <div id="section2" class="section"></div>
    <div id="section3" class="section"></div>
    <div id="section4" class="section"></div>

Answer №2

One way to achieve this is by utilizing the jQuery stop() Method

 $(".links a").click(function (e) {
  var hrefLink =  $(e.target).attr("href");
  var  hrefSplitted = hrefLink.split("#");
  if(hrefSplitted.length == 2){ 
     e.preventDefault();
  };
           /* if(! $(e.target).is('.links a:last') ){ 
               e.preventDefault();
             }*/
            
             $("html, body").stop();
            $("html, body").animate({
                scrollTop: $($(this).attr("href")).offset().top
            }, 1400)
        })
.links{
                width:600px;
                position:fixed;
                top:0;
                padding:20px;
            }
            .links a{
                display:inline-block;
                padding:10px 20px;
                border:1px solid #0094ff;
            }
            .section{
                width:400px;
                height:200px;
                margin:300px auto 600px;
                background-color:#0094ff;
            }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="links">
        <a href="#section1">Section 1</a>
        <a href="#section2">Section 2</a>
        <a href="#section3">Section 3</a>
        <a href="#section4">Section 4</a>
        <a href="http://google.com">External Link</a>
    </div>
    <div id="section1" class="section" style="background:red;"></div>
    <div id="section2" class="section"  style="background:blue;"></div>
    <div id="section3" class="section" style="background:green;"></div>
    <div id="section4" class="section" style="background:yellow;"></div>

Answer №3

In this example, using e.preventDefault() will prevent a link from following the URL:

$(".links a").click(function (e) {
    e.preventDefault();
});

However, using e.preventDefault() can lead to an issue with external links. To address this, you need to check if the href attribute starts with "#" before calling e.preventDefault():

$(".links a").click(function (e) {
    if ($(this).attr("href").charAt(0) == "#") {
        e.preventDefault();
    }
});

If you want to open external links in a new tab, you can do so by checking and setting the target attribute:

$(".links a").click(function (e) {
    if ($(this).attr("href").charAt(0) == "#") {
        e.preventDefault();
    } else {
        $(this).attr("target", "_blank");
    }
});

To prevent multiple clicks, use the stop() method. Here is the final code snippet:

The final code:

$(".links a").click(function (e) {
            if (this.getAttribute("href").charAt(0) == "#") {
                e.preventDefault();
                $("html, body").stop();
                $("html, body").animate({
                    scrollTop: $($(this).attr("href")).offset().top
                }, 1400)
            }
             else {
            $(this).attr("target","_blank")
        }
})
.links{
  width:600px;
  position:fixed;
  top:0;
  padding:20px;
}
.links a{
  display:inline-block;
  padding:10px 20px;
  border:1px solid #0094ff;
}
.section{
  width:400px;
  height:200px;
  margin:300px auto 600px;
  background-color:#0094ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="links">
    <a href="#section1">Section 1</a>
    <a href="#section2">Section 2</a>
    <a href="http://google.com" target="_blank">External Link</a>
    <a href="#section3">Section 3</a>
    <a href="#section4">Section 4</a>
</div>
<div id="section1" class="section"></div>
<div id="section2" class="section"></div>
<div id="section3" class="section"></div>
<div id="section4" class="section"></div>

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

Customizing hyperlink styles with JavaScript on click

Hey there! I'm experimenting with something new. I've managed to change the background color of each link after it's clicked, but now I'm facing a challenge: How can I revert the original style when another link is clicked? Here's ...

What is the process for combining JSON objects using the "id" key as the basis for merging

Having this json structure, my goal is to merge it based on the articleId. [{ "articleId": "45", "isA": false, "flags": { "isDema": fals ...

A recent challenge encountered with JavaScript involving incrementation

After successfully resolving my previous issue with the assistance of another user, I'm now encountering a new problem related to the following code snippet: const faker = require('faker'); const userList = require('./users.json') ...

Capturing user input by detecting the Enter key using jQuery

I am brand new to coding and struggling with capturing user input when the enter key is pressed. Currently, I have a submit button that successfully captures user input upon clicking. <div> <div class="text-area"> <li class=" ...

Unable to import an empty class, encountered error TS2307: Module 'menu' not found

I'm facing an issue where I am trying to import a basic, empty exported class. It seems like the file cannot be located even though it is in the same directory as the class that is importing it. I have looked up similar error messages on Google, but n ...

Mastering the art of chaining promises in Mongoose

I need help figuring out how to properly chain promises for a "find or create" functionality using mongodb/mongoose. So far, I've attempted the following: userSchema.statics.findByFacebookIdOrCreate = function(facebookId, name, email) { var self = ...

Modify a Google Docs script for use in Google Sheets

I created a function called "myFunk()" that works flawlessly in Google Docs. It essentially looks for fields marked with ## in a sheet and replaces them with user input. However, when I attempt to run it in Sheets after making some changes to the functions ...

Create an HTML table using data from a Python dictionary

Can anyone help me convert the dictionary below into an HTML table? {'Retry': ['30', '12', '12'], 'Station MAC': ['aabbccddeea', 'ffgghhiijj', 'kkllmmnnoo'], 'Download&ap ...

Tips for accessing the FormControlName of the field that has been modified in Angular reactive forms

My reactive form consists of more than 10 form controls and I currently have a subscription set up on the valueChanges observable to detect any changes. While this solution works well, the output always includes the entire form value object, which includ ...

Tips for confirming a sub string is present in an array using JavaScript/TScript

I am currently testing for the presence of a SubString within an array. In my test, I am asserting using: expect(classList).toContain('Rail__focused') However, I encountered the following error: Error: expect(received).toContain(expected // inde ...

Trouble with top attribute functionality within animate function

Why does the top attribute in the animate function of JQuery not seem to work, while the opacity attribute functions correctly in the code snippet below? $(function() { $(window).on('scroll', function() { ...

Update a roster with AJAX following the addition or removal of a user

My goal is to implement two functions: Adding and Deleting a User from the database using Mongoose. However, when I run the code, I receive a 200 OK response but with an empty username. I suspect there might be an issue with the ajax calls. Can anyone hel ...

Page cannot be adjusted to fit the viewport

My goal is to have the page fit perfectly within the viewport, but despite using the body properties below, I am still seeing a vertical scrollbar. body { display: grid; grid-template: .8fr 4fr / 1fr 4fr; max-height: 100vh; margin: 0; } I'm w ...

Plugin for controlling volume with a reverse slider functionality

I have been customizing the range slider plugin found at to work vertically instead of horizontally for a volume control. I have successfully arranged it to position the fill and handle in the correct reverse order. For instance, if the value is set to 7 ...

Why ASP .NET MVC's AJAX BeginForm InsertionMode.Replace feature is causing issues

When I input anything into the text field, I can see the result displayed in the desired DIV. However, upon inspecting the page's source code, I cannot locate the replacement element. For instance, if I input 'aaaaaaaaaaaaaaaa', then click ...

Utilize CSS to format the output of a script embedded within

When I embed the following script in my HTML, the output doesn't have any styling. How can I style the script output to blend well with the existing HTML structure? I tried accessing the output by ID, but couldn't figure it out. <script> ...

Identifying the selected element with jQuery

Let's say I have a form that includes both inputs and textareas. How can I determine which one is currently selected or clicked on? $('body').on('change', 'input textarea', function() { }) In simpler terms, ...

Using regular expressions, you can locate and replace the second-to-last instance of a dot character in an email address

I'm looking to replace the second last occurrence of a character in a given string. The length of the strings may vary but the delimiter is always the same. Here are some examples along with my attempted solutions: Input 1: james.sam.uri.stackoverflo ...

Mapping memory for FirefoxOS is like equivalent strides

Is there a way to create a memory mapped file in FirefoxOS, Tizen or other pure-JS mobile solutions? In the scenario of a mobile browser where you have large amounts of data that can't fit in RAM or you prefer not to load it all at once to conserve R ...

What steps should I follow to update this React Navigation v5 code to v6?

As I delve into my studies on React Native, I came across the deprecation of the tabBarOptions feature. I understand that now we need to include it in screenOptions, but I'm facing issues with implementing this in my code. I tried enclosing them in br ...