The jquery animation feature seems to be malfunctioning as the div element is not displaying

My goal is to create a div that smoothly appears and disappears while moving randomly, but I'm having trouble as it seems fixed in place. Below is a snippet of the code causing issues. Currently, the div only fades in and out. Any assistance would be greatly appreciated.

CSS

div.a {
    width: 50px;
    height:50px;
    background-color:red;
    position:fixed;    
}

JAVASCRIPT

 var opacidad = [0.0, 1.0];
 var visibilidad = ['hidden', 'visible'];
 $(document).ready(function () {
     animateDiv();
 });
 function makeNewPosition() {
     var h = $(window).height() - 50;
     var w = $(window).width() - 50;
     var nh = Math.floor(Math.random() * h);
     var nw = Math.floor(Math.random() * w);
     return [nh, nw];
 }
 function animateDiv() {
     var newq = makeNewPosition();
     var oldq = $('.a').offset();
     var speed = calcSpeed([oldq.top, oldq.left], newq);
     movement(newq, speed);
 };
 function movement(newq, speed) {
     var newqHalf = Math.floor(parseFloat(newq) / 2);
     $('.a').animate({
         top: newqHalf[0],
         left: newqHalf[1],
         opacity: opacidad[0]
     }, speed).css({
         visibility: visibilidad[0]
     })
     var newqDouble = Math.floor(parseFloat(newq) * 2);
   
     $('.a').animate({
         top: newqDouble[0],
         left: newqDouble[1],
         opacity: opacidad[1]
     }, speed)
     .css({
         visibility: visibilidad[1]
     }, function () {
         animateDiv()
     })
 }
 function calcSpeed(prev, next) {
     var x = Math.abs(prev[1] - next[1]);
     var y = Math.abs(prev[0] - next[0]);
     var greatest = x > y ? x : y;
     var speedModifier = 0.1;
     var speed = Math.ceil(greatest / speedModifier);
     return speed;
 }

Answer №1

Hey there, I've created a jsFiddle that may not be exactly what you were expecting, but it's based on your code and features random animations for position and opacity of the div. I've also made some corrections based on my previous comments.

UPDATE: I have made further adjustments to the Fiddle based on your feedback.

Here's what I've done:

  1. In the movimiento function, I incorporated calculations for the current position so that...
  2. ...we can determine the halfway point between the current and new coordinates
  3. I included an additional animation for the halfway point to smoothly transition opacity from 0 to 1.
  4. The easing is set to linear to ensure both half animations run at the same speed. Applying custom easing for the entire animation would be more complex.

UPDATE 2: Apologies for the mistake in calculating the halfway point. It has been corrected.

Check out the updated jsFiddle here!

Don't forget to call animateDiv(); to start the animation.

function makeNewPosition() {
    var h = $(window).height() - 50;
    var w = $(window).width() - 50;

    var nh = Math.floor(Math.random() * h);
    var nw = Math.floor(Math.random() * w);

    return [nh, nw];
}

function animateDiv() {
    var newq = makeNewPosition();
    var oldq = $('.a').offset();
    var speed = calcSpeed([oldq.top, oldq.left], newq);
    movimiento(newq, speed);
};

function movimiento(newq, speed) {
    var currq = [
        $('.a').offset().top,
        $('.a').offset().left
    ];
    
    var halfq  = [
        Math.floor(currq[0] + (newq[0]-currq[0])/2),
        Math.floor(currq[1] + (newq[1]-currq[1])/2)
    ];

    console.log("Animating from " +  + currq[0] + "," + currq[1] + " to: " + newq[0] + "," + newq[1] + " passing through: " + halfq[0] + "," + halfq[1] + " - at speed: " + speed);    
    $('.a').animate({
        top: halfq[0],
        left: halfq[1],
        opacity: 1
    }, {
        easing: 'linear',
        duration: speed
    });

    $('.a').animate({
        top: newq[0],
        left: newq[1],
        opacity: 0
    }, {
        easing: 'linear',
        duration: speed,
        complete: animateDiv
    });
}

function calcSpeed(prev, next) {
    var x = Math.abs(prev[1] - next[1]),
        y = Math.abs(prev[0] - next[0]),
        greatest = x > y ? x : y,
        speedModifier = 0.1,
        speed = Math.ceil(greatest / speedModifier);

    return speed;
}

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

What is the best way to extract the modal into its own file?

Greetings, fellow React developer who is new to the field! I have successfully implemented a React Class Component that includes a popup Modal. This Modal displays when a user clicks on an Item Card: import React from 'react'; import { Card, Bu ...

Enhance user experience with a dynamic Bootstrap combo box that updates based on

I am currently facing an issue with the bootstrap combobox plugin. I am having trouble changing the selection and sending that information from the view to the controller. $('#MyCombo').on('change', function () { var data = $(this) ...

Having trouble uploading big files on your Windows system?

My challenge is to successfully upload a large file using Angular. Specifically, I am attempting to upload a Human Genome tar file, which is a minimum of 2.5gb in size. Strangely, when I try to upload the file from Linux using any browser such as Chrome or ...

Having difficulty in animating the upward movement of textbox2

I've got a form that contains 2 buttons and 2 textareas. When the form loads, I want to display only section1 (button, textarea) and the section2 button. Upon clicking the section2 button, my aim is to hide the section1 textarea, reveal the section2 t ...

Displaying threaded discussions in React

Below is an array that contains comments, and I am attempting to display them in a threaded manner by utilizing the parentId property. comments: [ { id: 1, parentId: null }, { id: 2, parentId: 1 }, { id: 3 ...

sticky navigation bar at the top with content sections below linked with anchor tags

I am working on a design where my header-menu is set to fixed position. Within the menu, there are anchor links that scroll to different sections of the same page. However, when users click on these anchor links, the top part of the section is hidden by th ...

Are there any functions that work with an array of objects?

Is there a way to use includes function to check if an object is inside the array, as shown below: arr=[{name:'Dan',id:2}] When trying to check with includes like this: arr.includes({name:'Dan',id:2}) The result returned is false. I ...

Display a hidden div only when a cookie is set during the initial visit

I'm currently facing an issue while trying to set multiple cookies based on the existence of a div using JavaScript. On the first visit, I want to display the div to the user if it exists, then set a cookie (named redCookie) that expires in 3 days. Up ...

Switching back and forth between different rows within a table

Currently, I am just starting out with AngularJS (1.5) and I have come across a challenge that I am hoping to get some assistance with. I have a table that is generated dynamically and for each row, I need to add a down arrow in the first column. Based on ...

"Use jQuery to seamlessly alter the CSS clip-path property for smooth transitions

I have an element that utilizes css clip-path. By using jquery, I am able to adjust the clip-path points based on the cursor's X-coordinate position. While my code functions well, I am looking to add a smoother and slower transition to this "animatio ...

The hover CSS effect in the dropdown menu does not apply to sibling elements, but does work on descendant elements

Below are two sets of code for creating a dropdown menu. Although similar, the codes have a slight difference. In both cases, I have assigned classes to the main list item and submenu. The main heading has been given the 'heading' class with an a ...

The input value may contain certain characters at any position

An issue has arisen with my directive that is meant to validate an input field to ensure it does not include the characters &, <, > .directive('refValidate', [function () { var regExp = /^[&\<\> ]*$/; return { ...

What could be causing the failure to retrieve the salt and hash values from the database in NodeJS?

My current issue involves the retrieval of hash and salt values from the database. Although these values are being stored during sign up, they are not being retrieved when needed by the application. Below, you will find snapshots of the database, console s ...

Present a Java-generated JSON object on a JSP page using JavaScript

Hello, I am currently working on creating a Json object in Java and would like to display the same JSON object in JSP using JavaScript. Essentially, I am looking to add two more options in my select box using Ajax. The Ajax is being called and I can see th ...

Could you please ensure that the animation activates upon hovering over the "a" element?

Utilizing bootstrap, I have created the following code. I am looking to add functionality that triggers an animation upon mouseover of an img or a element, and stops the animation upon mouseleave. .progress-bar { animation: pr 2s infinite; } @keyfr ...

Tap on ClassName to activate

UPDATE: After receiving feedback from a commenter to revise some code, I have updated the code but it's still not working as expected. I am currently working on developing a chat feature similar to Facebook. The function of this chat is to retrieve t ...

Converting an array of 8-bit unsigned integers into a string without the

Currently, I am working on extracting JSON data from an HTML document stored in a Uint8 array. The process involves converting the array to text and then isolating the JSON within a script tag. To achieve this, I initially converted the array into text fo ...

Ways to ensure that text wraps to a new line when it exceeds the container's width

I am currently working on implementing a line of text within an ion-card element, but the challenge lies in the fact that the length of the text varies each time. In order to ensure that the entire text is visible and not cut off, especially on devices wit ...

Is it time for a thorough "npm update"?

When running npm update, it updates the items listed in package.json, but the dependencies of those items remain outdated. An alternative solution is to run npm update multiple times. At times, I find myself needing to run it 3 or more times before achiev ...

What triggers the firing of onAuthStateChanged() in a Netxjs application?

Hey everyone, I've encountered an issue with a useEffect hook in my root page.tsx file within a Next.js app. Specifically, on my /SignIn page.tsx, I've set up Google as a login provider using FirebaseAuth. When I log in with signInWithPopup, I ex ...