Is there a way to manipulate the direction of bouncing divs using a button?

I want to design a single button that can control the bouncing motion of my div elements. The initial configuration will have the space divs arranged in a static, straight line.

Once the button is clicked, the divs should start bouncing within their container.

Check out the JsFiddle

function hitLR(el, bounding) {
    console.log($(el).data('vx'), $(el).data('vy'))
    if (el.offsetLeft <= 0 && $(el).data('vx') < 0) {
        console.log('LEFT');
        $(el).data('vx', -1 * $(el).data('vx'))
    }
    if ((el.offsetLeft + el.offsetWidth) >= bounding.offsetWidth) {
        console.log('RIGHT');
        $(el).data('vx',  -1 * $(el).data('vx'));
    }
    if (el.offsetTop <= 0 && $(el).data('vy') < 0) {
        console.log('TOP');
        $(el).data('vy', -1 * $(el).data('vy'));
    }
    if ((el.offsetTop + el.offsetHeight) >= bounding.offsetHeight) {
        console.log('BOTTOM');
        $(el).data('vy', -1 * $(el).data('vy'));
    }
}

function mover(el, bounding) {
    hitLR(el, bounding);
    el.style.left = el.offsetLeft + $(el).data('vx') + 'px';
    el.style.top = el.offsetTop + $(el).data('vy') + 'px';

}

setInterval(function() {
    $('.bouncer').each(function(){

        mover(this, $('.bouncyHouse')[0]);
    });
}, 50);

Answer №1

To halt the movement, you can utilize the clearInterval() method.

For a practical demonstration, refer to this live example.

function stopMovement(el, bounding) {
  if (el.offsetLeft <= 0 && $(el).data('vx') < 0) {
    //console.log('LEFT');
    $(el).data('vx', -1 * $(el).data('vx'))
  }
  if ((el.offsetLeft + el.offsetWidth) >= bounding.offsetWidth) {
    //console.log('RIGHT');
    $(el).data('vx', -1 * $(el).data('vx'));
  }
  if (el.offsetTop <= 0 && $(el).data('vy') < 0) {
    //console.log('TOP');
    $(el).data('vy', -1 * $(el).data('vy'));
  }
  if ((el.offsetTop + el.offsetHeight) >= bounding.offsetHeight) {
    //console.log('BOTTOM');
    $(el).data('vy', -1 * $(el).data('vy'));
  }
}

function moveElement(el, bounding) {
  stopMovement(el, bounding);
  el.style.left = el.offsetLeft + $(el).data('vx') + 'px';
  el.style.top = el.offsetTop + $(el).data('vy') + 'px';
}

function shift() {
  $('.bouncer').each(function() {
    moveElement(this, $('.bouncyHouse')[0]);
  });
};
$htmlBackup = $('.bouncer').clone();
movementInterval = setInterval(shift, 50);
$('button').on('click', function(){
  if( movementInterval != 0){
    clearInterval(movementInterval);
    $('.bouncer').remove();
    $('.bouncyHouse').eq(0).append($htmlBackup);
    $htmlBackup = $('.bouncer').clone();
    movementInterval = 0;
  } else {
    movementInterval = setInterval(shift, 50);
  }
});
.bouncyHouse {
  height: 200px;
  width: 150%;
  background-color: black;
  position: relative;
}

.bouncer {
  position: absolute;
  width: 200px;
  color: white;
}

.bouncer:nth-child(2) {
  top: 30px;
  left: 100px;
}

.bouncer:nth-child(3) {
  top: 50px;
  left: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bouncyHouse">
  <button type="button">Click Me!</button>

  <div class="bouncer" data-vx='2' data-vy='-3'>
    <span>space</span>
  </div>
  <div class="bouncer" data-vx='-2' data-vy='2'>
    <span>space</span>
  </div>
  <div class="bouncer" data-vx='5' data-vy='2'>
    <span>space</span>
  </div>
</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

Handling a jQuery Ajax success callback when it fails

I am encountering an issue with my ajax post request where even though I have separate success, failure, and status code handlers, when the request fails with a 400 error, part of the success function is still being executed. Can someone provide insight in ...

Transferring information between Vue.js components via data emissions

Greetings from my VueJS Table component! <b-table class="table table-striped" id="my-table" :items="items" :per-page="perPage" :current-page="currentPage" :fields="fields" @row-clicked="test" lg >< ...

Audio issues plaguing audio playback on Discord

After spending two exhausting days, I am still trying to figure out what is going on. I am currently working on a Bot for my Discord Channel that should play an audio.mp3 file when a specific command, like !laugh, is entered. However, despite trying variou ...

Implementing a try-catch-finally block in Javascript to handle errors during JSON parsing appears to be ineffective

As someone relatively new to web scripting, I find the similarities between Java try-catch blocks and Javascript ones intriguing. However, my attempts at using them have yielded slightly different results than expected. Here is a snippet of code showcasing ...

What is the best approach in AngularJS for implementing a browser modal that returns a promise?

How can I implement a custom modal in my code that allows me to perform an action only after the user clicks 'okay'? var modalInstance = this.$modal.open({ templateUrl: '/app/tests/partials/markTest.html', controller: ['$sc ...

The red error text below the input becomes less visible when the input is focused on Windows, creating

My issue involves a basic input field and error validation message, both set against a dark background. The problem arises when the error text is displayed and I click on the input field - the error text suddenly loses contrast and appears "thinner." What& ...

Issue with onDblClick event in Angular5 and PrimeNG's p-listbox

I encountered an issue while using p-listbox's onDblClick event as it does not return the selected list element. Instead, the event object only contains the value of 'this'. {"originalEvent":{"isTrusted":true}} HTML Blockquote <!-- S ...

Unable to retrieve information from the firestore database

When trying to fetch documents from the firestore, I encountered an issue where it returns an empty array. However, when I run console.log(docs); outside of the declared function, it actually shows the array data. This problem arises because my useEffect f ...

What is the proper procedure for configuring Babel and executing "npm run dev" in the terminal without encountering the "ERROR in ./src/js/index.js" message?

My goal is to include the babel/polyfill with the index.js files using webpack. After completing the setup, I tried running "npm run dev" in the command prompt but encountered an error. The initial line of the error message said "ERROR in ./src/js/index.js ...

Utilizing Axios Instances for Authorization in Next.js Data Fetching

I am currently utilizing NextJS version 12.0.10 along with next-redux-wrapper version 7.0.5. I have implemented an Axios custom instance to store the user JWT token in local storage and automatically include it in every request, as well as to handle errors ...

Bring in a JavaScript function into NodeJS without the need for importing any extra dependencies

Is there a way to import a zero-dependencies function zdfun without loading all the other dependencies in the module/file foo.js where it resides? While the ideal solution would be to extract zdfun into its own module and import it into foo.js, this may n ...

tips for transferring a javascript function value to a label within a webform

Currently, I am in search of the latitude and longitude coordinates for a specific address input by the user. Upon clicking a button, the script provided below is triggered to display an alert with the latitude and longitude values: <script type="text/ ...

Is there a way to modify or add to the response object's methods in Express and Node.js?

When using middleware in Express, the framework passes both a res and a req object. These objects enhance the built-in ones from http.ServerResponse and http.ClientRequest respectively. I am curious about the possibility of overriding or extending methods ...

Is it possible to automatically close the modal by clicking outside of it

How can I make sure that my modal box only closes when clicking outside of it, and not when clicking on the buttons inside? I have a ref to the parent element that successfully closes the modal on click outside, but currently it also closes if I click on t ...

Exploring Bootstrap: the ins and outs of customizing styles

How can one determine which bootstrap styles need to be overridden when customizing the appearance? Is there a trick to identifying where to set styles in order for them to take precedence over bootstrap styles? For instance, I've been struggling fo ...

Ensure that only one menu with a specific class is open at any given time

My goal is to ensure that both menus cannot be open simultaneously. The desired behavior is as follows: When one menu is already open and you click on another, the first one should automatically close. For a better understanding of what I am trying to achi ...

Which is more recommended to use in AJAX (XMLHttpRequest) - eventListener or readyStateChange method?

As I revisited a video from WWDC12 discussing advanced effects with HTML5, I couldn't help but notice that for the demo they utilized req.addEventListener("load",callback,true) instead of the usual onreadystatechange. This made me wonder: what differ ...

Utilizing React Native for seamless deep linking with automatic fallback to a webpage, including the ability to pass

I am currently working on a project that involves a website built with React and a React-native app for camera functionality and data processing. On the website, there is a button that opens the camera in the React-native app through deep-linking. This pa ...

Xpath is effective in Chrome Dev Tools, but does not seem to be functioning properly in RS

I am currently engaged in a project that involves extracting an HTML table containing specific text ("Current Prison History:") from various URLs that vary based on individual ID. I have attempted to utilize CSS selectors for this task, but encountered a c ...

A Fresh Approach for Generating Unique UUIDs without Bitwise Operators

To generate UUIDs in TypeScript, I have implemented a method inspired by the solution provided on Stack Overflow. The code effectively converts JavaScript to TypeScript. generateUUID(): string { let date = new Date().getTime(); if (window.performa ...