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

Using the npm timepicker in Laravel 5.8 with precision and efficiency

Looking for some guidance here as a newcomer to installing packages in Laravel. I'm currently working on implementing the timepicker feature from . In order to do this, I've already executed the command npm i jquery-timepicker. However, I seem t ...

waiting for elements in Nightwatch.js using FluentWait

I am seeking assistance on implementing FluentWait using nightwatch.js. How can I achieve this? Within my project, I have a global.js file that includes: waitForConditionPollInterval : 300, waitForConditionTimeout : 5000, However, it seems like this ...

Tips for Modifying the currentUrl identifier in Angular 2

I am trying to change the ID property of my currentUrl object within my component. My goal is for the ID to update and then fetch the corresponding data based on that ID. However, I keep encountering this error message: "Cannot assign to read only propert ...

Develop a custom script function for every instance of a @foreach loop

I have a challenge where I need to style automatically generated table rows by clicking on a button. Currently, my code appears as follows: @foreach($tours as $tour) <tr id="{{$tour->id}}"> <td> {{$tour->tournr}} &l ...

Selenium Scrolling: Improving Web Scraping Efficiency with Incomplete Data Extraction

I have been attempting to extract product data from a website that utilizes JavaScript to dynamically render HTML content. Despite using Selenium, implementing scrolling functionality to reach the end of the page, and allowing time for the page to reload, ...

Typescript is throwing an error stating that the type 'Promise<void>' cannot be assigned to the type 'void | Destructor'

The text editor is displaying the following message: Error: Type 'Promise' is not compatible with type 'void | Destructor'. This error occurs when calling checkUserLoggedIn() within the useEffect hook. To resolve this, I tried defin ...

Is there an equivalent to Tomcat specifically designed for Node.js applications?

Looking for an application server that offers an administration interface to deploy node.js applications, access log files, and manage running applications with options to start, stop, restart, and monitor? ...

Extracting data from a tiered website within a specialized niche

I am currently attempting to scrape data from the webpage: "https://esco.ec.europa.eu/en/classification/skill_main". Specifically, I want to click on all the plus buttons under S-skills until no more plus buttons can be found, and then save the page source ...

Is there a way for me to dynamically decide whether to use the append or prepend function?

Utilizing jQuery to retrieve data from the controller and populate a calendar represented by a table with days in columns. Implementing functionality for navigating between previous week / next week, as well as previous day / next day. The four scenarios s ...

how to use jquery to indicate that a checkbox is selected

click here to see the image $(document).ready(function() { $('.editbtn').on('click', function(){ $('#editmodal').modal('show'); $tr=$(this).closest('tr'); var da ...

Retrieving data from a database using PHP and presenting it in a loop for showcasing in JavaScript

I am currently working on a code and trying to achieve the following output: { title:"<?php echo $sender_fullname; ?>", mp3:"link", }, I want to display this in JavaScript using PHP. // Include database require_once "db.php"; // Get email ...

Access nested objects in Javascript (Vue)

Struggling with a simple question as a beginner... I am dealing with an object of objects: monsters { place1: { monster1: { ... } monster2: { ... } } place2: { monster3: { ... } monster4: { ... } } } I ...

The Model-View-Controller framework ensures the storage of a diverse assortment of both preexisting

After implementing the technique shared on Steve Sanderson's blog, I now have a feature where I can dynamically add items to a list using jQuery. In my case, I have a list of vehicles associated with a specific person that is fetched from the databas ...

Testing the screen size automatically using Javascript

Hello everyone, I've implemented a JavaScript code that triggers an image to slowly appear and darken the background when a link is clicked. However, on an iPad, the background doesn't completely turn black as intended. The CSS specifies that the ...

The keyboard fails to open when trying to input text on a WKWebView

Is there a way to programmatically open the keyboard in a WkWebView for tel text input after a JavaScript function call? I want the keyboard to display for efficiency reasons when a certain input is activated, but it doesn't gain focus automatically. ...

I am encountering issues where none of the NPM commands are functioning properly even after updating the

For a few months, I have been using npm without any issues. However, once I installed python/django and created a virtual environment, npm stopped working altogether. An error message similar to the following is displayed: sudo npm install -g react-nativ ...

Prevent a div from sliding up when a certain element is in view

Here is the issue I am facing: I want the top div to slide up or down only when the mediaPlayerWrapper is present, and not when the content_text is visible. Both are generated using Ajax and PHP, but only one exists at a time. The code below works correctl ...

What is the best way to delete a specific date from local storage using Angular after saving it with a key

I'm attempting to clear the fields in my object (collectionFilter) from local storage using localStorage.removeItem('collectionFilter'). All fields are removed, except for the date fields. Please note that I am new to JavaScript and Angular. ...

What is the best way to obtain real-time DOM updates using jQuery?

Upon loading my webpage, various scripts are adding a significant amount of HTML code. Now, I am attempting to modify this additional HTML. For instance, there is a div element <div id="detail"><span>some content</span></div> that ...

Tips for displaying subtotal in a Vue application using Firebase Realtime Database

I am currently troubleshooting a method in my Vue app that is designed to calculate the total value of all items sold. Despite seeing the correct values in both the database and console log, the calculation seems to be incorrect. Could there be an issue wi ...