Unable to produce scrolling animation using JavaScript

I'm trying to implement a feature on my website where the page scrolls with a sliding effect when the user presses the "Scroll" button. However, I've encountered issues as it doesn't seem to work despite adding the necessary tags to my HTML file.

Even after finding a script that should enable this functionality, it still didn't work as expected.

Can anyone help me identify where I might be going wrong?

home.html

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script  src="{% static 'js/home.js' %}"></script>
    <link rel="stylesheet" href="{% static 'css/home.css' %}">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
.
.
.
    <section id="section01" class="demo">

      <h1> Welcome to PHARSYS  </h1>
      <h2>Scroll for Login or Signup</h2>

      <a href="#section02"><span></span></a>
    </section>
    <section id="section02" class="demo">
      <h1>Login</h1><br>
        <h2>Press the button to log in to the system.
      <br><br>

      </h2>
      <a href="#section03"><span></span>Scroll</a>
    </section>
    <section id="section03" class="demo">
      <h1>Signup</h1>
        <h2>Press the button to register to the system</h2>
    </section>

home.js

$(function() {
  $('a[href*=#]').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top}, 500, 'linear');
  });
});

home.css

@import url(https://fonts.googleapis.com/css?family=Josefin+Sans:300,400);
* {
  margin: 0;
  padding: 0;
}
html, body {
  height: 100%;
}
...

Answer №1

The issue was located here

$('a[href*=#]').on('click', function(e) { ...

If you want to select anchor elements with a href attribute starting with the # character, use ^ instead of *. This signifies that it should begin with the specified character, and remember to put parentheses around the search character like this:

$('a[href^="#"]').on('click', function(e) { ...

See example below:

Note: I purposely set the body height to 1000px for testing purposes.

$(function() {
  $('a[href*="#"]').on('click', function(e) {
    e.preventDefault();
    $('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top}, 500, 'linear');
  });
});
body {
  height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script  src="{% static 'js/home.js' %}"></script>
<link rel="stylesheet" href="{% static 'css/home.css' %}">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<section id="section01" class="demo">

  <h1> Welcome to PHARSYS </h1>
  <h2>Scroll for Login or Signup</h2>

  <a href="#section02"><span></span></a>
</section>
<section id="section02" class="demo">
  <h1>Login</h1><br>
    <h2>Click to log in to the system.
  <br><br>

  </h2>
  <a href="#section03"><span></span>Scroll</a>
</section>
<section id="section03" class="demo">
  <h1>Signup</h1>
    <h2>Click to register to the system</h2>
</section>

You can also utilize the * as a wildcard instead of ^, which will match anchor elements containing a # character anywhere in their href attribute, not just at the start.

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

Issue with retrieving the ID of a dynamically created element with jQuery

Whenever I try to execute my function to display the id for a click event of a tag that has items appended dynamically, the alert does not show the id. Instead, it displays 'undefined'. Can anyone help me figure out where I am going wrong? Here ...

Struggling to find solutions for debugging HTML codes in Visual Studio Code and linking my CSS page to my HTML page

I ran into some issues with linking my CSS stylesheet to my HTML pages. I tried using the <link rel="stylesheet" href="style.css"> command, where style.css is the name of the file. However, for some reason, it wasn't working ...

Rails: Ensure that JSON form fields remain populated in case the form encounters a validation error

I am using a rails simple form to create a product with three fields inside in order to associate it with appropriate categories: <div class="form-group"> <%= f.input :child_category_id, :collection => @categories.order(:name), :l ...

Tips for shifting the cursor slightly to the right within an Input field

I created a div with an input field inside. I set the input field to autofocus, so when the page loads, the cursor is automatically focused on the input field. However, the cursor is touching the border of the input field, making it hard to see clearly. ...

Unveil Information with Underscore JS

I am attempting to showcase my data in a table using Underscore.js. Below is the div container class I am working with: <div id="container"></div> Upon window load, I have added an event listener: window.addEventListener("load", function(ev ...

Missing transitive dependencies have been identified within the node_modules directory when using npm

In my software development journey, I am working on two npm projects - one called X and the other called Y. Let's say that X relies on angular and has it specified as a dependency in its package.json file. To establish a connection between X and Y, I ...

Exploring techniques for creating realistic dimensions in CSS

My goal is to create a responsive website that accurately displays an object with specified dimensions, such as a width of 100mm, regardless of the user's screen resolution. However, I am facing challenges in achieving this consistency across all devi ...

Unable to store the data retrieved from MySQL into an array

Every time I try to add the object result1 to the array a, it ends up empty. Can someone help me figure out what I'm doing wrong? app.get('/freezer', (req, res) => { var a = []; var sql = `SELECT freezer_id FROM freezer_data`; ...

Having trouble navigating the dependency graph: Unable to locate module './crypto_auth' in sodium-universal

Encountering the following error while trying to browserify a node project from https://github.com/datproject/sdk: Error: Can't walk dependency graph: Cannot find module './crypto_auth' from 'C:\myPath\node_modules\sodium ...

Issue with custom fonts not showing in PDFs when using Puppeteer, even though they are displayed in screenshots

I've been working on dynamically creating PDF files using the puppeteer library, but I'm facing an issue where the generated PDF doesn't display the custom fonts (.woff) that I have specified. Instead, it defaults to using the system font, T ...

The issue of resolving NestJs ParseEnumPipe

I'm currently using the NestJs framework (which I absolutely adore) and I need to validate incoming data against an Enum in Typscript. Here's what I have: enum ProductAction { PURCHASE = 'PURCHASE', } @Patch('products/:uuid&apos ...

Using the built-in http module in node.js to upload images via multipart/form-data

I have encountered an issue where I need to send two images and an API key as part of a multipart/form-data HTTP request to an API. The images are retrieved from an AWS S3 bucket, which works fine. However, when attempting to send the image data as part ...

Is it possible for a PHP form to generate new values based on user input after being submitted?

After a user fills out and submits a form, their inputs are sent over using POST to a specified .php page. The question arises: can buttons or radio checks on the same page perform different operations on those inputs depending on which one is clicked? It ...

Ways to update row background color based on specific column values

I need to customize the background color of my table rows based on the value in the "Category" column. For example: Name Category Subcategory A Paid B C Received D If the Category value is 'Paid', I want the ro ...

My HTML grid table is not being properly rendered by the JSON data

I'm currently facing a challenge with rendering my HTML grid table in Angular using JSON data retrieved from a MySQL database. I would greatly appreciate any assistance or guidance on how to solve this issue. View the output of the Angular code here ...

Header-driven redirection

I am using node js and express js. My goal is to ensure that if app.get does not have a token parameter, then an html file with js will be uploaded to pass the token. If the token is passed, then another html file should be displayed. However, I am unsure ...

How to toggle between two background colors in a webpage with the click of a button using JavaScript

I need help with a unique website feature. I want to implement a button that cycles between two different background colors (white and black) as well as changes the font color from black to white, and vice versa. My goal is to create a negative version of ...

Navigate to the initial visible element on the specified webpage via the page hash link

In my handlebars HTML template, I have a partial view that includes different pieces of content for desktop and mobile. I use different CSS classes to hide and show these elements accordingly. <div class='hideOnMobile showOnDesktop'> < ...

Unable to fetch permissions for user:email via GitHub API

Currently, I am utilizing node-fetch to fetch an OAuth2 token from an OAuth2 GitHub App. The obtained token allows me to successfully retrieve user information from "https://api.github.com/user". However, I also require the email address, which necessitate ...

Tips for integrating Chart.js into my AngularJS application?

I am a beginner with AngularJS and I'm currently developing an application on Ubuntu. While trying to add Chart.js using npm install chart.js, an error is being displayed as follows. npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_emai ...