Animating a div to continuously move back and forth in jQuery

My goal was to have a div move continuously left and right when the page loads. However, I mistakenly made it so that the movement only occurs on click events. The code snippet below shows what I initially wrote:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>

<a href="" class="left">left</a> | <a href="" class="right">right</a>
<br /><br />
<div id="foo" style="background:red;width:100px;height:100px;position:absolute"></div>

<script> 
$('.right').click(function(e) {
    e.preventDefault();
    $('#foo').css({ 'right': '0px', 'left': '' }).animate({
        'right' : '30px'    
    });                    
});

$('.left').click(function(e) {
    e.preventDefault();
    $('#foo').css({ 'right': '', 'left': '0px' }).animate({
        'left' : '30px'
    });                    
});
</script> 

Answer №1

To achieve this effect, you can utilize CSS animations.

#bar {
  background: blue;
  width: 150px;
  height: 150px;
  position: absolute;
  left: 0;
  animation: moveRight linear 3s infinite alternate;
}

@keyframes moveRight {
  to {
    left: 100%;
    transform: translateX(-100%);
  }
}
<div id="bar"></div>

Answer №2

The `auto` values are not being correctly assigned automatically by jQuery or the browser.

Consider using the following approach:

$('.right').click(function(e) {
  e.preventDefault();
  $('#foo').css({ 'right': window.innerWidth - $('#foo').position().left - $('#foo').width(), 'left': 'auto' }).animate({
    'right' : '30px'
  });
});

$('.left').click(function(e) {
  e.preventDefault();
  $('#foo').css({ 'left': $('#foo').position().left, 'right': 'auto' }).animate({
    'left' : '30px'
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<a href="" class="left">left</a> | <a href="" class="right">right</a>
<br /><br />
<div id="foo" style="background:red;width:100px;height:100px;position:absolute"></div>

If you want it to automatically handle either action on page load, you can do this:

$(function () {
  function a() {
    $('#foo').css({ 'right': window.innerWidth - $('#foo').position().left - $('#foo').width(), 'left': 'auto' }).animate({
      'right' : '30px'
    }, function () {
      $('#foo').css({ 'left': $('#foo').position().left, 'right': 'auto' }).animate({
        'left' : '30px'
      }, a);
    });
  }
  a();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<br /><br />
<div id="foo" style="background:red;width:100px;height:100px;position:absolute"></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

Ways to restrict the maximum length in Draft.js

Is there a way to control the maximum number of characters in draft js? I know how to get the length of the state, but is there a method to prevent the component from being updated past a certain point? var length = editorState.getCurrentContent().getPla ...

Utilizing mobile emulators to optimize the viewport for mobile application development

Are mobile emulators like MITE() able to detect viewport settings? <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> Can anyone recommend a mobile emulator that does recognize viewport settin ...

Try implementing a body template when using the mailto function

Is there a way to customize an HTML template for the mailto() function body? For example, suppose I have the following link: echo "<a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97f2faf6fefbd7f0faf6fefbb ...

Incorporate HTML file into Chrome Extension by utilizing JQuery in JavaScript

I'm facing a challenge in creating a chrome extension that can modify the HTML of a webpage. I've set up four files for this project: manifest.json: { "manifest_version": 2, "name": "Agor.aio h3cks scrubz lel", "description": "Dis sext ...

Opening a browser tab discreetly and extracting valuable data from it

Greetings to the experts in Chrome Extension development, I am exploring ways to access information from a webpage without actually opening it in a separate tab. Is there a method to achieve this? Here's the scenario: While browsing Site A, I come a ...

Utilize the $(#id).html(content) method to populate the following column with desired content

Here is a snippet of my HTML code: <div class="row margin-top-3"> <div class="col-sm-7"> <h2>NFTs</h2> <div class="table-responsive"> <table class="table table-bordered&qu ...

Key Enhancements for Functional Stateless Components

How can I accurately assign a key in a functional component, specifically using the 'key' keyword instead of just a general index? I am attempting to use Map in a functional component to generate a list of another element. However, when I try to ...

React Router V6 - page is not found in browsing history

Currently, I am encountering an issue with react router v6. While on the detail page, if I press the arrow in Chrome to go back to the previous page, it takes me to the page before the previous one. I checked the history by long pressing on the back arrow, ...

jQuery is mistakenly showing a width of zero

When attempting to determine the width of specific elements using jQuery's .width() function, I occasionally encounter a return value of 0 unexpectedly. Could this be a common problem? Is it possible that an element must be visible in order for this f ...

What steps can I take to modify my webpage, like a dashboard, on the internet?

Whenever I click on a menu item in the sidebar of my HTML file, I want only the body section to change without affecting the navigation or sidebar content. For instance, if I select the "Coding Convention" menu in the sidebar, I would like the page to swi ...

Include the title of the page in the printing stylesheet

Is there a way to dynamically insert the page title into the print version of my website using jQuery and CSS? I have a separate print.css file, but I'm wondering if it's possible to grab the title data as a variable in jQuery and then use CSS to ...

Ajax failing to trigger upon submission

I need assistance in creating a form that will first submit via AJAX before directing to a specified URL. Once submitted, an email should be sent to me through newsletter.php <script type='text/javascript'> $(function () { $("#signup") ...

Learn how to import MarkerClusterer from the React Google Maps library without using the require method

The sample provided utilizes const { MarkerClusterer } = require("react-google-maps/lib/components/addons/MarkerClusterer");, however, I would prefer to use the import method. I attempted using: import { MarkerClusterer } from 'react-google-maps/lib ...

incorporating a personalized API feed into a news ticker

Looking for help with setting up a ticker on my website to display headlines from my custom news API. I'm a bit lost on where to start, so any guidance would be appreciated. Here's the API link - API Link Is there a simple solution for this? Cu ...

Using javascript to eliminate a block of HTML code

In my AngularJS project, I am using owl-carousel and attempting to reinitialize the carousel after a change in data by using $(element).data('owlCarousel').destroy(); while also removing this block: <div class="owl-wrapper"> <div class= ...

Harness the power of asynchronous programming by incorporating the async await method within

Within my Node Express application, I am looking to retrieve all comments associated with a particular lesson and enhance each comment by including a fullname field. To accomplish this, I have created a function called findFullNameByUserId in the UserContr ...

Guide on incorporating Bootstrap JS into HTML5 reusable web elements

RESOLVED: the solution is in a comment TL;DR: Issues triggering Bootstrap's JS, likely due to incorrect import of JS scripts I've been working on integrating Bootstrap with my custom reusable web components across all pages. Specifically, I&apo ...

Component failing to refresh with each key modification

My understanding is that adding a key attribute to a component should make it reactive when the key changes. However, with a v-navigation-drawer from Vuetify, this doesn't seem to have any impact. I've tried making arbitrary changes to the logge ...

Say goodbye to using 'jQuery .load()' with <img> elements inside <a> tags

I have a static HTML page and some other files with the same structure but different content. <div id="textRed" class="scrollbar"> <h1>Header</h1> <p>Lorem Ipsum</p> <a href="images/image1.jpg" data-lightbox ...

Having difficulties showing selectors content in Cheerio

Seeking assistance with extracting a table from a website, specifically trying to retrieve all the columns first. When I make the request and load the html into cheerio, I am facing an issue where the selector content does not display anything on the conso ...