Variable value reversal during callback execution

Is there a way to accomplish this? To start, take a look at the following code...

 function flutter() {
    var random = Math.floor(Math.random()*5);
    var $obj = $('.bird');
    $obj.animate({ top :'-=' + random + 'px' }, 20, flutter);
    } 
</script>

In the above code snippet, my objective is to reverse the value of random when the callback is executed. The end goal is to create a fluttering effect by moving the Class bird up and down.

Answer №1

If you want to add some animation effects, you can achieve it using the following closure method:

$obj.animate({ top :'-=' + random + 'px' }, 20, function(){ 
   flutter(random*-1);
});

Here is the complete code snippet for your reference:

function flutter(offset) {
    var random = ( isNaN(offset) ) ? Math.floor(Math.random()*5) : (offset) ;
    var $obj = $('.bird');
    $obj.animate({ top :'-=' + random + 'px' }, 20, function(){ 
       flutter(random*-1);
    });
 } 

To initiate the animation, simply call: flutter();

Answer №2

I made some modifications to the flutter function in order to enhance its efficiency and user-friendliness.

 function flutter(distance, target) {
    // You can now invoke flutter without providing arguments, eliminating the need for repetitive element finding
    var random = distance || Math.floor(Math.random()*5);
    var $obj = target || $('.bird');
    $obj.animate({ top :'-=' + random + 'px' }, 20, function(){
        flutter(-random, $obj);
    });
    } 

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

Tips for personalizing tooltips in Bootstrap 4

Currently, I am utilizing Bootstrap '4.0.0-alpha.6' and attempting to customize the tooltip styles. Despite adding a custom CSS class along with using Bootstrap 4, the tooltip is not responding correctly to my specified style when hovering over. ...

Updating the options list of an Autocomplete component post-render: A step-by-step guide

I've encountered an issue with a function that retrieves a JSON array from a URL containing a list of options to be displayed in my Autocomplete component. function DisplayOptions() { async function GetOptions() { options_list = await fetc ...

What are some methods for utilizing the data received through this.props.history?

Whenever I need to navigate from one route to another using this.props.history.push("/"), I also want to pass along some extra data. For example: this.props.history.push('/postDetail', {data: item}). However, I am uncertain about where to define ...

Issue with HTTP POST Headers in XmlHttpRequest

I am currently attempting to pass a string using the XmlHttp method. Let me provide you with the code for better understanding: HTML <div id="greetings"> You are voting out <b style="color: #00b0de;" id=roadiename></b>. Care to explain ...

Replace all occurrences of $regex in Node.js with the json data format

Here is a JSON example var json= { name: { '$regex': /^Amer$/i }, 'countries.name': { '$regex': /^UNited states$/i } } I am looking to reformat it using either lodash or string/json replace method to achieve the following st ...

Steps to stop POST requests sent via AJAX (acquired through Firebug)

Is there any way to protect against users spamming a post request? Consider a scenario where a form is submitted through an Ajax post. I've observed that the post request can be duplicated by simply right clicking on it and choosing "open in a new tab ...

a timing mechanism that halts at a pre-determined point in time

Looking to create a countdown timer that begins at 8AM EST and ends at 6PM EST. Once the timer reaches 00:00:00, I'd like to hide the control on the website and have it reappear at the same time the next day. Any suggestions on how I can make this hap ...

Combining href into click events - a step-by-step guide

I have an href link available. '<a href="index.php?imei=' + value['imei'] + '&nama=' + value['nama'] + '" class="summarykapal">Summary</a>' This is the function in question: function retr ...

Vertical scrolling causes the bottom of the sidebar to be cut off

If you take a look at the following Tailwind CSS, you'll notice that when you scroll down, the sidebar is not fully visible at the bottom. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> ...

Achieving dynamic page number display in relation to Pagination in ReactJS

I have a website that was created by someone else, and the pagination feature is becoming overwhelming for me as I am not a coder or developer. Image Link Currently, my navigation pagination displays 17 pages. I would like to limit this to only showing 1 ...

Guide to fetching external data with Next.js and importing the component into a different file

I have implemented the following code in my pages/github file, and when I navigate to localhost:3000/github, the code runs successfully and returns JSON data. function GithubAPI(props) { // Display posts... return (<div>{props.data.name}</div& ...

Using Ruby on Rails to incorporate AJAX for posting and commenting functionality

Could use some assistance with implementing AJAX into my project. It seems like it should be a simple task, but I've been struggling with it for days. My goal is to have new comments appear without the need to reload the page. Below are references to ...

How can PHP send a variety of error messages to an Ajax/Jquery script and display them in an HTML DIV?

In an attempt to send various error messages back to an HTML DIV based on the PHP outcome, I have scoured through different resources without a solution that fits my particular case. Hopefully, someone can provide assistance with this. The scenario involv ...

Tips for positioning two divs in the center of a webpage, both horizontally and vertically, while also including a header and

Currently, I am in the process of creating a new web page with Bootstrap 4. This page consists of four main elements - a header, a footer, and two content boxes contained within divs. While I have successfully utilized default bootstrap classes to ensure t ...

Strip away the HTML tags and remove any text formatting

How can I effectively remove HTML tags and replace newlines with spaces within text? The current pattern I am using is not ideal as it adds extra space between words. Any suggestions on how to improve this pattern? replace(/(&nbsp;|<([^>]+)> ...

Text is not visible when hovering over it

I am facing an issue with the hover effect on my menu element. When I hover over the element, the text does not appear as expected. Even after using z-index to position the text on top, it still doesn't work. Here is a snippet of my code: HTML: < ...

Tips for decreasing Vuetify Grid column width on larger screens

I'm currently utilizing the vuetify grid system to construct a reply component. The column ratio is set at 1:11 for the icon and reply columns, respectively. Below you'll find the code snippet: <v-row justify="center" class="ma-0 pa-0"> ...

Determine the Size of an Image File on Internet Explorer

Is there an alternative method? How can I retrieve file size without relying on ActiveX in JavaScript? I have implemented an image uploading feature with a maximum limit of 1 GB in my script. To determine the size of the uploaded image file using Java ...

Tips for eliminating padding at the top and bottom of a navigation bar

I'm looking to remove the top and bottom padding from my navbar to give it a similar look to the navbar on Wix.com. I've spent most of today trying to figure this out. I've attempted to remove padding with !important from the navbar, tried u ...

clear JavaScript array of elements

I've been grappling with this issue for hours now, and it seemed so straightforward at first; My goal with JavaScript is to iterate through an array, retrieve the current index value, and then remove that value from the array. I've read that spl ...