Using jQuery to create a dynamically moving div that forms an endless wall

In order to create a continuous wall that pulls text from a database and displays it, I've developed the following code:

$(function() {
    var x = 0;
    var y = 100.0;
    var z=0;
    setInterval(function() {
        x -= 0.1;
        y -= 0.1;
        z++;
        if (x <= -100.0){ 
            $("#h1d1").html("loop div 1 :" + z);
            x = 0;
        }
        if (y <= 0){
            $("#h1d2").html("loop div 2 :" + z);
            y = 100.0;
        }
        $('#movimg1').css('left', x + "%");
        $('#movimg2').css('left', y + "%");

    }, 10);
    $("#stopbutton").click(function() {
        $('#movimg1').stop();
    });
})

However, the behavior of the text is not as desired, changing in the middle of the screen when it should update only when out of view. https://jsfiddle.net/oa0wdxcx/2/

I also aim to incorporate a play/pause button. Any tips on achieving this functionality would be greatly welcomed. Additionally, I'd like the divs to be contained within the #wrap div, but altering the position attribute to relative causes them to move apart.

Thank you in advance.

Answer №1

The issue stemmed from the conditions.

            if (x <= -100.0) {
                z++;
                $("#h1d1").html("loop div 1 :" + z);
                x = 100; /* modify this line */ 

            }
            if (y <= -100.0) { /* modify this line */ 
                w++;
                $("#h1d2").html("loop div 2 :" + w);
                y = 100;

            }

The conditions dictate that if either of these two divs reaches left:-100%, the element should be placed at the end of the queue with left:100%.

Additionally, you can streamline these if statements and utilize only x for the transition.

To ensure the start and stop buttons function correctly, terminate the simulation using the clearInterval() function to stop, and invoke doSimulate() to restart:

        var started = true;

        $("#stopbutton").click(function () {
                if(started) {
                    clearInterval(sim);
                    $(this).html('Start');
                    started = false;
                } else {
                    doSimulate();
                    $(this).html('Stop');
                    started = true;
                }
            });

Check out the functioning Start/Stop feature on jsFiddle here.

Answer №2

Take a look at this JSFiddle link where I have added an additional element to achieve a seamless transition back to the starting point. The third element should display the same message as the first one.

HTML Section

<body>
    <div class="row">
        <div class="col-xs-1"></div>
        <div id="wrap" class="col-xs-10">
            <div class="movimg message1" id="movimg1">
                 <h1 class="header">start div 1</h1>
            </div>
            <div class="movimg message2" id="movimg2">
                 <h1 class="header">start div 2</h2>
            </div>
            <div class="movimg message1" id="movimg3">
                 <h1 class="header">start div 1</h1>
            </div>
        </div>
        <div class="col-xs-1"></div>
    </div>
    <div class="row">
        <button class="button" id="startbutton" style="display:none;">Start</button>
        <button class="button" id="stopbutton">Stop</button>
    </div>
</body>

JavaScript Part

$(function () {
    var x = 200.0;
    var interval;

    function start(){
        interval = setInterval(function () {
            x -= 0.1;
            if (x <= 0.0) {
                x = 200;
            }
            $('#movimg1').css('left', (x-200) + "%");
            $('#movimg2').css('left', (x-100) + "%");
            $('#movimg3').css('left', x + "%");
        }, 10);
    }

    start();

    $("#stopbutton").click(function () {
        window.clearInterval(interval);
        $(this).hide();
        $("#startbutton").show();
    });

    $("#startbutton").click(function () {
        start();
        $(this).hide();
        $("#stopbutton").show();
    });
})

CSS Styles

body {
    overflow: hidden;
}
#wrap {
    width: 80%;
    left: 10%;
}
.movimg{
    position: absolute;
    height: 600px;
    width: 100%;
    background-image: url('https://s-media-cache-ak0.pinimg.com/736x/89/ed/e5/89ede56bcc8243787e55676ab28f287f.jpg');
}
#movimg1 {
    left: 0%;
}
#movimg2 {
    left: 100%;
}
#movimg3 {
    left: 200%;
}
.header {
    text-align: center;
}
.button{
    top: 600px;
    position: relative;
}

LATEST UPDATE:

Introducing Stop and Start buttons: Check out the updated version on JSFiddle

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

Show a few values as a string in Angular using Typescript

I am working with JSON data and I want to know how to display hobbies without including the word "all" in an Angular/TypeScript application. { "Name": "Mustermann1", "Vorname": "Max1", "maennlich& ...

Element in Vue not displaying when modal is hidden

Having trouble displaying a Vue component on a modal controlled by semantic ui. The Vue element is not loading or mounting properly. My setup involves Laravel and jQuery with some Vue elements intertwined. I have a hunch that the issue stems from the moda ...

managing the AJAX server's response

Struggling with a seemingly simple project where a button click should display a random saying generated from PHP, I don't have access to the PHP code and feel a bit lost. The issue seems to be in how I'm handling the server response (the handleS ...

What is the best way to use Shadcn to incorporate a calendar that takes up half of my website?

Currently, I am in the process of developing a scheduling appointment system. My main challenge is getting the calendar to take up half of my page's space. Despite my attempts to adjust its height and width, I have not been successful in seeing any ch ...

typescript push in react native is a crucial step to enhance performance and optimize

I've been diving into TypeScript within the realm of React Native. Oddly, when I translated a certain snippet to vanilla JavaScript, the application worked flawlessly. However, upon converting it back to TypeScript, an error message popped up stating ...

Is there a way to duplicate and insert a function in node.js if I only have its name?

I'm currently working on a code generation project and I've encountered a problem that I initially thought would be easy to solve. However, it seems to be more complicated than I anticipated. My task involves taking a method name as input, naviga ...

Retrieve a photo from a website address and determine its dimensions

When grabbing an image from a URL using this function: const fetch = require("node-fetch"); function getImageFromUrl(url) { return fetch(url).then((response) => response.blob()); } To determine the dimensions of the images, I am utilizing ...

Utilizing ionic-scroll for seamless movement and scrolling of a canvas element

I have set up a canvas element with a large image and I want to enable dragging using ionic-scroll. Following the provided example: <ion-scroll zooming="true" direction="xy" style="width: 500px; height: 500px"> <div style="width: 5000px; h ...

I am looking to showcase a text directly from the properties file using the thymeleaf template engine

I have two files named message_ar.properties and messages_fr.properties for internationalization purposes. Within my HTML file, I am attempting to show the correct label for a confirm message. To accomplish this, I am utilizing Thymeleaf as my template e ...

Leverage an HTML table to serve as a data source for populating a Kendo UI template

My latest creation is a unique service that generates HTML tables based on request parameters. The current implementation returns the data as an HTML page in string format. Here's a sample output: <!DOCTYPE html> <html> <head> ...

Concealing certain elements within a loop using a "show more" button

In my PHP code, I am utilizing a foreach loop in the following manner: <div class="items"> @foreach($results as $details) <div class="col s2 l2"> {{ $details }} </div></div> My approach involves using the blade templating feature ...

Tips for accessing elements with dynamically assigned IDs in jQuery

I'm working on an ASP.Net MVC project and came across the following code: @Html.DropDownListFor(m => m.users, @Model.User, new { id = "UserIds" + @Model.ID }) What is the best way to retrieve the id of this element? ...

What is the best way to align the button correctly beside the cluster of checkboxes within bootstrap framework?

Here is a snippet of HTML code that I am working with: <div class="container"> <form name ="queryForm"> <div class="form-group"> <p class="checkbox-inline"> <input type="checkbox" name="optionsRadios" id="checkOne" ...

I desire to share the JSON information and receive the corresponding response data

<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> ...

Display a preview image at the conclusion of a YouTube video

I am currently working on an iOS device and have a Youtube video thumbnail that, when clicked, disappears and the video automatically plays in fullscreen mode using an iframe. It's working perfectly. Now, I would like to know how I can make the thumb ...

I am encountering an issue where propData in Vue Jest is returning as undefined

I have encountered an issue while passing the propData in my jest test file for a Vue component. It seems that the propData is not being set to the component and instead, I am receiving an error saying "cannot read property of clouds of undefined." Could i ...

Comparing the use of jQuery click event with the button to trigger a function that calculates the

Currently, I am grappling with a JQuery function that checks if any checkboxes are ticked within my form. My version of JQuery is v1.10.2. The code functions as expected when triggered by a button, but when I attempt to trigger it with a checkbox within t ...

What is the best way to create a dynamic JavaScript counter, like one that counts the world's population

Can someone guide me on creating a real-time JavaScript count-up feature that doesn't reset when the page reloads? Any tips or examples similar to would be much appreciated. Thank you! ...

Retrieve the host name using the getStaticProps method

Can the hostname be accessed within the getStaticProps function? export async function getStaticProps(context) { // retrieving the hostname const hostname = ???? } ...

I'm having trouble getting this button and icon to align properly. How can I fix this misalignment

Take a look at the HTML code snippet I'm currently working on... <div id="projects"> <H1 class="projects">PROJECTS</H1> <div class="box"></div> <div class="box"></div> <div class="box"></ ...