Adjust the top position of a div element at regular intervals

How can I make the top position of an absolutely positioned div with children change every x seconds using jQuery? I tried using setInterval but it only changes once. Here is my code:

.com_prices {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #dd0d0d;
  position: relative;
} 
.com_tabs {
  position: absolute;
  height: auto;
  width: 100%;
}
.com_price_tab {
  width: 90%;
  margin: 10px auto;
  height: 100px;
  background: #fff; 
}

The HTML

<div class="com_prices">
    <div class="com_tabs">
      <div class="com_price_tab"></div>
      <div style="background: #28bc88" class="com_price_tab"></div>
      <div style="background: #fff000" class="com_price_tab"></div>
      <div style="background: #333" class="com_price_tab"></div>
      <div style="background: #28bc88" class="com_price_tab"></div>
      <div style="background: #999" class="com_price_tab"></div>
      <div class="com_price_tab"></div>
      <div class="com_price_tab"></div>
    </div>
  </div>

The script

 setInterval(function() {
    $('.com_tabs').animate({top: "-100px"}, 350);
 }, 2000);

Answer №1

Make sure to adjust the top position correctly by subtracting 100px from the current position.

 var $comtabs = $('.com_tabs');
 setInterval(function() {
    var top = parseInt($comtabs.css("top"));
    $comtabs.animate({top: top - 100 + "px"}, 350);
 }, 2000);

Here's a live example for reference:

var $comtabs = $('.com_tabs');
setInterval(function() {
  var top = parseInt($comtabs.css("top"));
  $comtabs.animate({
    top: top - 100 + "px"
  }, 350);
}, 2000);
html,
body {
  background: #000;
  height: 100%;
  margin: 0;
  padding: 0;
}

.com_prices {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #dd0d0d;
  position: relative;
}

.com_tabs {
  position: absolute;
  height: auto;
  width: 100%;
}

.com_price_tab {
  width: 90%;
  margin: 10px auto;
  height: 100px;
  background: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="com_prices">
  <div class="com_tabs">
    <div class="com_price_tab"></div>
    <div style="background: #28bc88" class="com_price_tab"></div>
    <div style="background: #fff000" class="com_price_tab"></div>
    <div style="background: #333" class="com_price_tab"></div>
    <div style="background: #28bc88" class="com_price_tab"></div>
    <div style="background: #999" class="com_price_tab"></div>
    <div class="com_price_tab"></div>
    <div class="com_price_tab"></div>
  </div>
</div>

Answer №2

The issue lies in the fact that the top position is being set to -100px. Each time the function runs, it attempts to set the top position to a value that is already (-100px), resulting in no visible change. To fix this, you can retrieve the current top value and subtract 100px from it. Here's an example:

setInterval(function() {
    var $el = $('.com_tabs');
    var top = $el.css('top');
    var topNumber = top.substr(0, top.length -2) - 100;
    console.log(topNumber);
    $el.animate({top: topNumber + 'px'}, 350);
}, 2000);

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

When using a callback function to update the state in React, the child component is not refreshing with the most recent properties

Lately, I've come across a peculiar issue involving the React state setter and component re-rendering. In my parent component, I have an object whose value I update using an input field. I then pass this updated state to a child component to display t ...

To prevent the loss of form data, consider utilizing the input type button instead of the button element

I'm a bit hesitant to repost my question, but it appears that my initial query (Why won't my jquery display correctly) may have slipped through the cracks. My apologies for the lengthy block of code, but I'll include it all in hopes of provi ...

What is the time complexity for finding a specific value in a two-dimensional matrix?

The challenge at hand is quite straightforward: develop an algorithm that can determine if the target value exists within the given matrix. Here, I have devised two potential solutions. However, I am uncertain as to which one would be more efficient. Perso ...

The enigmatic jQuery AJAX glitch is craving additional arguments

My website uses jQuery's ajax function to handle user signups. Despite using similar code throughout the site, I encountered an error while trying to execute the code below: Error Message: uncaught exception: [Exception... "Not enough arguments" nsr ...

Is it possible to implement Autocomplete functionality without relying on JQuery UI?

Is it possible to implement autocomplete without relying on JQuery UI due to its large footprint, including CSS? Are there any alternative plugins available? I have searched extensively but have not come across any. ...

Retrieve data from MongoDB using the find() method results in an empty response, however,

While working on a project to practice my MongoDB skills, I encountered an issue with retrieving all the data from MongoDB. Despite receiving a successful 200 response, I was unable to properly extract all the data. Using Express framework for this task, ...

Adjust Navbar Header Color Based on Screen Size

I am completely new to front-end development. I am in the process of building my own responsive website using Bootstrap 3. One issue I am facing is that when I resize my browser window to simulate a phone screen, I want the navigation bar color to change ...

Steps for running a function upon activation of a React Router:

I'm currently using Reacter Router to manage the routes of my application. For authentication, I am utilizing an OAuth system that provides my application with the following URL: http://localhost/login-meli?code=1234567890 Every time this particular ...

Transforming the hide/show functionality from JQuery to Vue

I created some hide/show panels using jQuery that I want to implement in Vue. However, when I try to integrate the jQuery functions into Vue, the functionality doesn't seem to work properly. The panels are not hiding/showing as expected. Does anyone ...

Having trouble parsing the BODY of a NodeJs JSON post request?

I've been working on creating a basic API using nodeJS, but I've run into a problem while trying to post data. Below is my app.js file: const express = require('express'); const feedRoutes = require('./routes/feed'); const ...

I'm curious about using NextJS to fetch an API with a specific router ID. Can anyone provide guidance on how to achieve this and then render the data as HTML?

Greetings! I am currently coding in NextJS and working on a user page that fetches user-specific information from an API. My goal is to extract the ID query from the URL and use it to make an API request. The API endpoint follows this structure: /Users/{i ...

Tips for utilizing an object key containing a dash ("-") within it

Here is an example of the object structure: { approved_for_syndication: 1 caption: "" copyright: "" media-metadata: (3) [{…}, {…}, {…}] subtype: "photo" } How can I properly a ...

Issues with jQuery .submit() function not functioning properly following an ajax request

I am having an issue where I want to automatically submit a form if a certain condition is true, but for some reason it's not working as expected. I have tried debugging with firebug, but the form isn't getting submitted and I can't figure o ...

Populate an HTML layout with MySQL information and dynamically add the content to the page using JavaScript

I'm facing a challenge with creating an about us page for a website. I am using a template to structure the page and I want to populate it with MySQL data. I have enclosed the entire <div> of the personcard within a <script> tag, but the p ...

What is the best way to access the data stored within a Promise object in a React application?

Below is the snippet of my code that handles parsing application data: async function parseApplication(data: Application) { const fieldGroupValues = {}; for (const group of Object.keys(data.mappedFieldGroupValues)) { const groupValue = data.mappedF ...

The Google Docs viewer is displaying an empty screen

I have been utilizing the Google Docs viewer on my website: <div class="embed-r embed-responsive-a"> <iframe class="embed-responsive-it" src="https://docs.google.com/viewer?embedded=true&amp;url=http://LINK.PDF"></iframe> </div& ...

Encountering a challenge when trying to showcase data from a saved .txt file within a bootstrap card

I encountered a minor problem in my PHP project. I developed a small application that allows users to fill out form fields and stores all the data in a .txt file. Simultaneously, the entered data is displayed below the form with specific details such as fi ...

How to populate a database with Facebook data by utilizing AJAX post and PHP

I've been developing a Facebook Canvas game and had it running smoothly on my localhost along with a local database via phpMyAdmin. However, after moving it online, I've encountered an issue with the database. Previously, the game would grab pla ...

Tips for automatically setting focus to the following cell after inserting a new row in AngularJS

Transitioning from the Knockout world to Angular, I am facing an issue with a key-press event for tab. Whenever I add a new row in the table, the focus shifts to the information icon in the URI bar instead of the next cell in the newly created row. I belie ...

Displaying the product quantity counter in the shopping cart immediately after adding the item

My website has a shopping cart quantity counter that doesn't update immediately when a product is added. Instead, it requires a page reload or navigation to another page for the change to be reflected. I would like the quantity counter to show the pro ...