What is the best way to have the image smoothly slide from the left 0,0 position all the way to the far right side?

I am working on a piece of code that involves moving an image across the screen. The current code I have is:

   <script type="text/javascript">
      var animate, left=0, imgObj=null;

function init(){

   imgObj = document.getElementById('myImage');
   imgObj.style.position= 'absolute';
   imgObj.style.top = '240px';
   imgObj.style.left = '-300px';
   imgObj.style.visibility='hidden';

   moveRight();
}

function moveRight(){
    left = parseInt(imgObj.style.left, 10);
    if (10 >= left) {
        imgObj.style.left = (left + 5) + 'px';
        imgObj.style.visibility='visible';

        animate = setTimeout(function(){moveRight();},20);

    } else {
        stop();
    }
}

function stop(){
   clearTimeout(animate);
}

window.onload = function() {init();};
   </script>
<img id="myImage" src="http://newsxpressmedia.com/files/radar-simulation-files/radar007339.Gif" style="margin-left:170px;" />

The current functionality moves the image from the left side to the center of the screen. However, I would like it to start at the top left corner and move all the way to the right top border, continuously looping back. Unfortunately, changing the values to 0 only made the image static in its position.

I am also interested in adding more images to create a continuous sliding effect from left to right. How can I modify the code to achieve this?

Answer №1

Here's a suggestion for you:

<script>
    var animate, left=0, imgObj=null, right;

    function initialize(){

       imgObj = document.getElementById('myImage');
       imgObj.style.position= 'absolute';
       imgObj.style.top = 0;
       imgObj.style.left = 0;
       imgObj.style.visibility='visible';

       right = document.documentElement.clientWidth - imgObj.width;
       moveRight();

    }

    function moveRight(){
        if (left < right) {
            left += 5;
            imgObj.style.left = Math.min(left, right) + 'px';

            animate = setTimeout(moveRight,20); // call moveRight in 20msec
        }
    }

    window.onload = initialize;
</script>
<img id="myImage" src="http://newsxpressmedia.com/files/radar-simulation-files/radar007339.Gif" />

Check out the DEMO here

Moving on to your second inquiry:

How can I incorporate more images to continuously slide from left to right?

To make it work with multiple images, tweak the code slightly as follows:

<script>
    var imgObjs=null;

    function initialize(){
       imgObjs = document.getElementsByTagName('img');
        for(var i = imgObjs.length; i--; ) {
           var imgObj = imgObjs[i];
           imgObj.style.position='absolute';
           imgObj.style.top = 0;
           imgObj.style.display='none';        
        }

       animateImages(0);
    }

    function animateImages(i) {
        var imgObj = imgObjs[i],
            right = document.documentElement.clientWidth - imgObj.width;

        left = imgObj.style.left = 0;
        imgObj.style.display='block';

        function moveRight(){
            if (left < right) {
                left += 5;
                imgObj.style.left = Math.min(left, right) + 'px';

                setTimeout(moveRight,20); // call moveRight in 20msec
            } else {
                imgObj.style.display='none';
                animateImages((i+1)%imgObjs.length);
            }
        }
        moveRight();
    }

    window.onload = initialize;
</script>
<img src="http://newsxpressmedia.com/files/radar-simulation-files/radar007337.Gif" />
<img src="http://newsxpressmedia.com/files/radar-simulation-files/radar007338.Gif" />
<img src="http://newsxpressmedia.com/files/radar-simulation-files/radar007339.Gif" />

See the DEMO here

Answer №2

Utilize a combination of javascript and css transition to achieve optimal results

<style>
    img {
        position: absolute;
        width: 100px;
        height: 100px;
        left: 0;
        top: 0;

        transition-property: left;
        transition-duration: 2s;
    }
</style>

<img src="pic.jpg">

<script>
    function animate() {
        var img = document.getElementsByTagName('img')[0];
        var img_width = 100;
        var window_width = window.innerWidth;
        img.style.left = window_width - img_width;
    }

    function init() {
        setTimeout(animate, 1000);
    }

    window.onload = init();
</script>

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

Avoiding the interference of various elements positioned in a fixed manner

Is there a way to position two divs on a page without hard coding margins or padding? One div has fixed positioning at the top of the page with style="position:fixed; left:0; top:0;right:0;", and the other has fixed positioning to the left of the page wi ...

I'm having trouble understanding why I'm getting an error when trying to link CSS or SCSS

<link rel="stylesheet" type="text/css" href="scss/styles.scss"> <link rel="stylesheet" type="text/css" href="css/styles.css"> /*webpackconfig.js*/ var path = require("pat ...

Output each element of an array in Vuejs2 with a line break between each

I am currently working with vuejs2 and have a select tag where a person is selected, with their address properties directly bound to the element. I need to display the address of the selected person. I attempted to use an array in order to print out the el ...

Display the MediaStream on a WebGLRenderer

It may sound a bit unusual, but how can you display a video stream var videoStream = new MediaStream(stream.getVideoTracks()); using var renderer = new THREE.WebGLRenderer({antialias: true, alpha: true}); renderer.setSize(640, 480); ...

Is there a way to align this text in the middle of the div vertically? The usual methods are not proving to be effective

I noticed that on the following website (), the text is currently padded at the top which is determining its height. I am looking to modify this in order to vertically center it within the div, however, the standard CSS properties do not seem to be effecti ...

Adding a contact form to a slider: A step-by-step guide

Currently, I am faced with the challenge of placing my form on a slider in such a way that the slider appears to be running in the background of the form. When using position absolute, I find myself having to apply excessive margins and top pixels due to t ...

Excluding <select> elements with empty <option> values in jQuery SerializeArray: A simple guide

Within my HTML form, there is a section containing the <select> element: <form id="fruits"> <input type="text" name="title" value="some_title"/> <select name="color"> <option value="">all</option> <optio ...

Finding a specific element within a Node.js application requires pinpointing and isolating

I have a dynamic table that displays user information, with each row containing an update icon and a delete icon. When the delete icon is clicked, I need to delete the corresponding user record. The challenge is identifying which user's delete icon ha ...

Unexpected behavior encountered when implementing specific Textfield validation with Material UI

Currently running a project on Node and utilizing React for the front-end, I have encountered an issue with setting .env variables. The project is built with Material UI, and most TextFields are working as expected with their specified validation rules. ...

Assess the AJAX Response within Puppeteer

As I delve into using puppeteer, I find myself at a crossroads with a question: When I navigate to a site and click on a button, an ajax request is made to the server which brings back a message to display on the homepage. I want to verify the response re ...

What methods can I implement to prevent my boxes from becoming stretched out?

How can I prevent this box from stretching too much? Here is the code snippet along with the output: CSS: .social { padding-left: 1000px; border: 5px inset black; margin: 4px; width: 100px; } HTML: <div class="social"> <p& ...

Converting to lower case with Jexl and making replacements in the text

Currently, my code uses the jexl.eval function to evaluate a value like so: jexl.eval("dataset[0].data['Entity Name'].toLowerCase().replace(/ /g, '_')", data); The value of dataset[0].data['Entity Name'] is always a ...

Having trouble getting your custom Angular directive to function properly with dynamically changing images?

Currently in the process of developing a custom directive for AngularJs that involves an image rotator based on a Jquery Plugin I created, you can check it out here Below is the code snippet for my directive: .directive('imageRotator', function ...

Design custom CSS for the buttons inside one specific jQuery dialog among many on the same page

I am trying to specifically style the buttons within one jQuery dialog out of multiple dialogs on my page. Typically, I would target all dialog buttons using: .ui-dialog .ui-dialog-buttonpane and .ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset H ...

Overlay popup within iframe doesn't appear at the forefront of the page

I am facing an issue with displaying overlay and popup within an iframe on my aspx page. The iframe is calling another aspx page that includes the overlay and popup div elements. When I click a button within the iframe, the overlay and popup appear but t ...

Netlify encountered an error with mixed content, indicating that the page was successfully loaded over HTTPS, but it attempted to request an insecure HTTP

hey everyone, Recently, I deployed my vue-cli website project on Netlify. However, upon opening the website, I encountered the following error message: Mixed Content: The page at 'https://xxxx.netlify.app/' was loaded over HTTPS, but requested a ...

"Encountering issues with $compile not functioning properly within a

I'm struggling with my AngularJS directive that involves calling $compile within a click() function callback. Despite my efforts, the contents are not being compiled as expected. var testApp = angular.module('testApp', []); testApp.control ...

jQuery function failing to produce the intended results

I am trying to apply the active class to the last img element using HTML and jQuery Below is my code in HTML and jQuery: function initialSteps() { $(".row").find("column:last").find("img:first").className += " active"; // this does not work either ...

Please verify the utilization of jQuery.ajaxSettings.xhr

var _orgAjax = jQuery.ajaxSettings.xhr; jQuery.ajaxSettings.xhr = function () { var xhr = _orgAjax(); DoSomeLogging(); return xhr; }; I came across this code snippet and I'm trying to make sense of it. Does this mean that any $.ajax(...) ...

Expanding on the number of touchdowns can be achieved by using HTML and PHP to iterate through array elements

I am searching for a way to dynamically add table rows and cells based on the number of elements in my PHP array. Specifically, I have 4 arrays that are populated with numbers from a text document using a PHP script. This part is working correctly. Now, I ...