How to create a moving div using JavaScript ? Read Courses Practice Improve Improve Improve Like Article Like Save Article Save Report issue Report In this article, we will learn to create a moving HTML div using JavaScript. The div will move left to right using HTML, CSS, and JavaScript. Approach: We have to create an HTML div and add some CSS to the div using a glass ball. In CSS, we add some background-color to the body and give some height, width, and color to the div. Now we will add margin-left to the div using JavaScript. So it will move left to right. In JavaScript, we grab the div using the id name. And after some interval of time, we will add margin-left to the div. Example: In this example, we are using the above-explained approach. HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <style> body { background-color: aqua; display: flex; align-items: center; } .ball { height: 12rem; width: 12rem; background-color: white; border-radius: 50%; margin-top: 20rem; } </style> </head> <body> <div class="container"> <div class="ball" id="ballID"></div> </div> <script> let ball = document.getElementById("ballID"); var myVar = setInterval(spostaDiv, 90); var margin = 0; let l = window.screen.width; let w = 1300; function spostaDiv() { console.log(w); if (margin == w) { margin = 0 + "px"; } else { ball.style.marginLeft = margin + "px"; } margin += 10; } </script> </body> </html> Output: Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now! Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore. Last Updated : 08 May, 2023 Like Article Save Article Previous How to center a div within another div? Next How to stretch div to fit the container ? Share your thoughts in the comments Add Your Comment Please Login to comment...