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() {
          var top = $(this).scrollTop();
          $('#lan').animate({
            top: top + 'px'
          }, 1000);
        });
      });
<!DOCTYPE html>
        <html lang="en">
        
        <head>
          <meta charset="UTF-8>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
          <title>Test</title>
        </head>
        
        <body>
          <div id="lan">My First Dangerous</div>
        </body>
        
        </html>

Answer №1

In this demonstration, we aim to showcase the effectiveness of the "animate" function.

To achieve this, it is necessary to specify the "position" property of the "element" as either "absolute", "relative", or "fixed". For example, position: fixed;

$(function() {
  $(window).on('scroll', function() {
    var top = $(this).scrollTop();
    $('#lan').animate({
      top: top + 'px'
    }, 100);
  });
});
body {
  min-height: 2000px
}

#lan {
  position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="lan">My First Dangerous</div>

Answer №2

Check out the code on CodePen

$(function() {

  $(window).on('scroll', function() {
    var top = $(this).scrollTop();
    $('#lan').animate({
      top: top + 'px'
    }, 1000);
  });
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <title>Test</title>

<style>

body{
  height: 800px; 
  overflow:scroll;
}
#lan{
  position:relative;
}

</style>

</head>

<body>

  <div id="lan">My First Dangerous</div>

</body>

</html>

Answer №3

Are you looking to create an element that stays visible in the viewport while also having a scrolling animation effect?

It can be quite amusing!

To achieve this, the element needs to have its position set to absolute so it follows the document's scrollTop position. Using fixed for positioning ties the element to the viewport.

However, implementing an animation on scroll can be tricky. The scroll event fires rapidly and queuing animations for every scroll event will lead to a chaotic display. To address this, you can use a flag to check if the animation has already been triggered by a previous scroll event and prevent further triggers.

Additionally, adding a delay after scrolling ends can help ensure the animation runs smoothly. My suggestion is a 400ms delay paired with a fast 100ms animation duration. This combination enhances user experience and minimizes discrepancies in the final position due to continued scrolling.

While not flawless, it offers a functional solution.

$(function() {

  // Flag variable
  scrolling = false;
  
  // Variable to store scrollTop position
  var top;
  
  // Scroll handler
  $(window).on('scroll', function() {

    // Update top position on scroll
    top = $(this).scrollTop() + 10;
    
    // Prevent further execution until current animation finishes
    if (scrolling) {
      return;
    }

    // User is scrolling
    scrolling = true;
    
    // Delay before initiating animation
    setTimeout(function() {

      // Animate!
      $('#lan').animate({
        top: top + 'px'
      }, 100, function() { 
        scrolling = false;
      });
      
    }, 400);  
  });
});
body {
  min-height: 2000px
}

#lan {
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="lan">My First Dangerous</div>

Answer №4

Make sure to insert the <script></script> tags before closing the </body> tag, not within the head section. Hopefully, this solution works for you!

<!DOCTYPE html>
<html lang="en">    
<head>
  <meta charset="UTF-8>
  <title>Test</title>    
</head>    
<body>    
  <div id="lan">My First Dangerous</div>    
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>    
</html>

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

One more time: Utilizing AJAX to save the outcome in a variable with the help of callback (undefined)

I am facing a common problem and despite my efforts, I cannot seem to resolve it. The code snippet I have provided below is causing me trouble: function get_network_from_database(callback) { $.ajax({ type: "POST", url: "load_network.ph ...

Using socket.io to filter MongoDB documents by their unique object IDs

I am facing an issue where I need to retrieve a specific document from a MongoDB collection using the object ID when working with Socket.io. Since `findById()` is not effective in this case, and I am unable to use `find({ "_id" : _id})`, I am unsure about ...

The PrimeNG Tree component offers a range of unique features

Encountering an issue with the PrimeNG tree in angular2 Let's take a look at the code snippet from product_tree.component.ts : constructor(private http: HttpClient, private productsService: ProductsService) { this.productsService.getProductsClasse ...

Angular: What is the best way to populate a column in a table with individual dropdown menus in each cell, each containing unique values?

I am completely new to Angular and I am attempting to build a table to display user information. <div ng-controller="ContactController as cc" ng-app="MyApp" id="account-settings-page"> <div class="slds manage-account-table"> <table class="s ...

Four unique chip/tag colors, personalized to suit your style

Currently, I have integrated two arrays into my autocomplete menu where the chip/tag color is either primary or secondary based on the array the selected component belongs to. I aim to include all four arrays in the menu (top10Songs, top10Artists, top10Fi ...

Insert title into PDF document

I am currently working on a react application that generates PDF documents easily. The libraries I have utilized are: jspdf html2canvas Below is the code snippet that demonstrates my approach: index.js: <div className="App"> < ...

Express backend not receiving form data from post request

I recently created a form to submit a file to an express backend, but I'm encountering an issue where the data is not being received on the backend when the form is submitted. Upon using console.log, I noticed that req.body returns {}, and sampleFile ...

Return an array with only emails included

Looking to sort through an array specifically for emails, I attempted the following action emails = emails.filter((x)=>(x !== (undefined || null || ''))) To remove any empty values, while still allowing non-email values. ...

Modify vanilla JavaScript carousel for compatibility with Internet Explorer

I am currently in the process of creating a website that incorporates a carousel similar to the one found at the following link: https://codepen.io/queflojera/pen/RwwLbEY?editors=1010 At the moment, the carousel functions smoothly on opera, chrome, edge ...

How can you ensure that this intricate text on the page is verified using Selenium with Java?

I need to confirm if the following HTML code is present on the page, which contains // characters, etc. I am using selenium and Java for this task. <div class="powatag" data-endpoint="https://api-sb2.powatag.com" data-key="b3JvYmlhbmNvdGVzdDErYXBpOjEyM ...

Steps to prepend a domain to file_get_contents function in PHP script

Recently, I enlisted the help of a PHP coder to make modifications to two files for me. The purpose was to allow users to link directly to a file converted from DOC to IMG on . Below you can find the edited code (highlighted by 'DrTech76'): get ...

What causes the discrepancy between the nodejs package on GitHub and the version downloaded through npm?

After committing to installing a nodejs package with npm install -g package_name, I noticed that some of the downloaded packages have different files compared to the same package on Github. Why is this discrepancy present? ...

Post Request to Express API does not produce any output

Today, I encountered an issue while trying to create a JWT authentication API in Express. When I send a POST request with Postman, it only returns {}. Below is the code for server.js: const express = require("express"); const mongoose = require("mongoos ...

Updating by clicking with auto-prediction feature

I have implemented an autosuggestion feature to display results from a database table while typing in an HTML field, and I am looking to utilize JavaScript to post another value from the same row where the autosuggested values are stored. https://i.stack. ...

I'm having trouble getting FlowType.js to function properly

I have added the following code just before the closing </body> tag, but unfortunately, it seems like the type is not changing as expected. I am struggling to identify what mistake I might be making. Check out FlowType.JS on GitHub View the code on ...

Waiting for a method to finish in Node.js/Javascript

Currently, I am in the process of creating a trade bot for Steam. However, I have encountered an issue where the for-loop does not wait for the method inside it to finish before moving on to the next iteration. As a result, the code is not functioning as i ...

Is there a way to customize the CSS for a single blog post and add a 5-star rating system without affecting other posts?

After launching my blog on Google's Blogger, I wanted to add a unique touch by incorporating a static 5-star rating system in my Books I Read Section. I thought about using CSS to customize each book post and display anywhere from 1 to 5 stars for vis ...

Display errors in Jqgrid retrieved from JSON data

I am facing an issue where I need to display error messages by fetching information from a JSON response. Whenever we make changes (add/edit) in jgrid, we expect a JSON response with data. If there is an error in adding something, the response will include ...

Showing outcomes by making rapid consecutive AJAX requests

If you need a visual representation, I have a PHP script for a Hotel Management application that showcases a calendar (with columns representing days of the month and rows displaying prices per day). This script can be accessed in edit mode, where it gene ...

Accessing a variable from an external JavaScript file using jQuery

Can someone help me out with this issue I'm facing? I am having trouble getting a string returned to a variable in my embedded Javascript code. token.js: function token () { return "mysecretstring"; } HTML Code: <!DOCTYPE html> <h ...