Sliding a div with JavaScript

I've been searching for a solution to make a div slide to the side after 2 seconds using JavaScript, but I haven't found one that quite fits what I'm looking for. Here's my current code:

setTimeout("slide()", 1000)

function slide() {

  var myElement = document.querySelector("#box");
  myElement.style.left = 200px;

  setTimeout("slide()", 2000)

};
#box {
  position: absolute;
  left: 100px;
  top: 100px;
  width: 300px;
  height: 300px;
  background: blue;
}
<div id="box">box</div>

If there's anything wrong with my approach or if you can point me in the right direction with a helpful resource, it would be greatly appreciated! Thanks

Answer ā„–1

To make the correction:

myElement.style.left = '200px';

Instead of:

myElement.style.left = 200px;

And for this change:

setTimeout(slide, 2000);

Instead of using:

setTimeout("slide()", 2000);

Answer ā„–2

When using setTimeout, make sure to pass a function as its first argument rather than a string. Additionally, avoid misfires by taking note of the ()

To correctly utilize setTimeout, follow this format:

setTimeout(slide, 1000);

function slide() {

  var myElement = document.querySelector("#box");
  myElement.style.left = '200px'; // Be mindful of this!

  setTimeout(slide, 2000)

};

Answer ā„–3

Incorrect usage of the setTimeout function can be rectified by utilizing a style string.

setTimeout(function(){slide();}, 1000);
function slide() {
  var myElement = document.querySelector("#box");
  myElement.style.left = "200px";
  setTimeout(function(){slide();}, 2000);
}

Alternatively, you can simplify it to:

setTimeout(slide, 1000);
function slide() {
  var myElement = document.querySelector("#box");
  myElement.style.left = "200px";
  setTimeout(slide, 2000);
}

The first option is preferable if you need to pass parameters like so:

setTimeout(function(){slide(2000);}, 1000);
function slide(delaytime) {
  var myElement = document.querySelector("#box");
  myElement.style.left = "200px";
  setTimeout(function(){slide(delaytime);}, delaytime);
}

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

Is there a way to instantly show the contents of a newly opened tab in BootstrapVue?

Good day, my objective is as follows: Whenever a new tab is opened, it should become 'active' and display its content on the browser Issue: Currently, when a new tab is opened, the previous tab remains 'active'. Check out a simple e ...

Updating jQuery event behaviors based on the value of .html( 'string' )

Visit this link for more information. Feel free to modify the heading if you believe it needs improvement. General I manage a multilingual WordPress website with dynamic menu and navigation controlled through the WordPress admin panel. The multilingual ...

Automatically sending form submission after 5 seconds

I'm facing an issue with submitting a form after the page loads and 5 seconds have passed. I've tried using setTimeout but it doesn't seem to be working. Can anyone suggest why this might be happening? jQuery and delay() also don't work ...

Issue: The serializer is receiving more than one value for the 'instance' argument

Recently, I started working with Django My current project involves performing CRUD operations using serializers, but I encountered this particular error: Here is the function in question: def updateemp(request, id): Updateemp = EmpModel.objects.get( ...

Tips for displaying content when clicking on the opener containing tables or div elements

This is a snippet of JavaScript code $(document).ready(function () { $(".show-content").hide(); $(".opener").click(function () { $(this).parent().next(".show-content").slideToggle(); return false; ...

How to deactivate an option in md-autocomplete

I encountered a scenario where I converted an md-input-container with a md-select/md-option to a md-autocomplete. While in the initial setup of md-select/md-option, we were able to apply ng-disabled property to both the md-select and md-option. However, wh ...

Tips for retaining the original text value even after clicking the submit button

import java.util.Map; import java.util.HashMap; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org ...

There are certain lines of JavaScript/Node.js code that are failing to execute

app.get is not being executed. I have also attempted to include app.listen(3000). My goal is to retrieve the parameter passed from the first web page. This code is designed to fetch parameters sent by another web page and then construct a MySQL query and ...

Developing 2 potential results from textarea input using NODE.JS and HTML

Today, I encountered an issue while working on my bot website project that responds to textarea input. When I attempted to test it with two different commands, one of the commands stopped working unexpectedly. I'm puzzled by this and would greatly app ...

Interacting with JSP through session management

Hello, I am working on a JSP program that involves displaying a number along with a button. The objective is to have the displayed number increment whenever the user clicks the button. Sessions are also intended to be included in this program. Here is wha ...

Encountering error notifications when attempting to install Node npm

Iā€™m currently in the process of setting up these npm packages: npm I express body-parser bcrypt cors dotenv gridfs-stream multer multer-gridfs-storage helmet morgan jsonwebtoken mongoose Regrettably, each time I try to download them, an error seems to o ...

Manipulate the 'i' variable within a for loop using JavaScript, JQuery, and JSON to modify an attribute

I have 4 picture locations saved in a JSON file named img0, img1, img2, and img3. By using an AJAX call (getJSON), I retrieve the data from the file and then assign them to the "src" attribute of the images on my webpage. Everything works fine with this c ...

Turn text 90 degrees creating a div that is positioned inside its parent container

Whenever I rotate text (or a div containing text), it seems to break free from its parent container. Additionally, the height of the div appears to be based on its original width after rotation. I prefer using CSS to achieve the desired outcome rather than ...

Struggling to reach global variables in AngularJS?

Based on the inquiry found in this source: Global variables in AngularJS It has been suggested that global variables can be set using a service or rootscope. My issue lies in the fact that I am unable to access the global variable within a function, unle ...

Adjust the top value of a tooltip in Foundation 4

How can I adjust the tool tip text top value to avoid it hovering over icons? To get a clearer view of the issue, check out the screenshots provided. If you notice any other formatting issues with my HTML text, please don't hesitate to inform me. (Jus ...

All promises in the Promise.all() function are resolved instantaneously

I am currently attempting to execute a series of actions after uploading multiple images, utilizing Promise.all. However, I have noticed that the code following the then statement is running before the dispatched code. Where am I going wrong in my unders ...

Java and Selenium: Struggling to Find Element based on Attribute

Attempting to click a button on a webpage with the given HTML code: <html lang="en" webdriver="true"> <head> <body class="scbody" style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAKCAYAAAB10jRKAAAAGXRFWHRTb2 ...

What is the most effective method for obtaining data from a user and transmitting it to the game's processing system?

[Lance] Seeking the most effective way to extract information from a listener and transfer it to the game engine. Currently working on making the Spaceship follow my mouse movements. I have created a MouseControls.js file that listens for mouse movement an ...

Utilize JQuery to implement fading effects for clicked elements in a webpage

I've been using a rollover JavaScript plugin to create smooth transitional effects when users hover over clickable page elements. Everything was going well until I decided to switch to making ajax calls instead of page loads for dynamic content. The p ...

Issues have been reported regarding compatibility between iOS7, jquery.touchSwipe, on click and webkit-touch-callout

I'm in the process of developing a web application, but I've encountered an issue with iOS7 where there seems to be a conflict between jquery.touchSwipe and my "on click" events. Interestingly, the web app functions perfectly on older iOS versio ...