Div element to animate and vanish in a flash

I'm attempting to create a smooth slide effect for a div element before it disappears. Below is the code I am currently using:

function slideLeft(element) {
  $("#" + element).animate({
    left: "510"
  }, {
    duration: 750
  });
  document.getElementById(element).style.display = "none"; 
}

When I remove the last line of code, the div smoothly slides to the left over 750ms. However, adding the line causes the div to simply vanish.

I tried inserting the following before the last line:

wait(750);

The 'wait' function was defined as:

function wait(ms)
{
  var d = new Date();
  var d2 = null;
  do { 
    d2 = new Date(); 
  } while(d2-d < ms);
}

Unfortunately, this resulted in the div lingering for 750ms before disappearing abruptly. My goal is for the div with the ID of 'element' to gracefully slide and then disappear with display:none. Any suggestions or ideas on how to achieve this? Thank you.

Answer №1

To fully utilize jQuery's animate method, make sure to include the complete option. Additionally, if you already have the object at hand, there is no need to search for it again. Simply employ the this keyword within your complete function to apply additional animations directly to the object.

$("#" + current_my).animate({ left: "510" }, { duration: 750 }, function() {
   $(this).hide();
});

Answer №2

To ensure the div is hidden properly, it's recommended to hide it within the complete callback function.

function slide_in(current_my)   {
   $("#" + current_my).animate({
      left: "510"
    }, 750, function() {
        document.getElementById(current_my).style.display = "none";
    });
}

Check out this documentation for more details.

Answer №3

After the animation completes, Animate provides a callback function that can be utilized for further actions.

function slide_in(current_my)   {
    $("#" + current_my).animate({
         left: "510"
    }, {
         duration: 750
    }, function () {
         document.getElementById(current_my).style.display = "none"; 
    });
}

Answer №4

If you're looking for an alternative method, consider using animate.css. Simply adjust the animation duration in the CSS file to customize your animations.

$(document).ready(function() {
$('button.btn').click(function() {
  $('div.box').addClass('animated fadeOutLeftBig');
  });
});
.box {
  width: 50px;
  height: 50px;
  margin-left: 200px;
  background-color: red;
}

.box p {
  text-align: center;
  font-size: 1em;
}

div.box {
  -webkit-animation-duration: 5s;
  -webkit-animation-delay: 0s;
  -moz-animation-duration: 5s;
  -moz-animation-delay: 0s;
  -ms-animation-duration: 5s;
  -ms-animation-delay: 0s;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
  <p>Test</p>
</div>
<button class="btn">Fade Left</button>

Answer №5

Let's add a twist to the request and make it more entertaining. Instead of using a function, let's introduce an event to initiate the animation by passing location and duration values just for fun:

$(document).on('slidehide', '.myanimate', function(event, requestedDuration, whereTo, shouldHide) {
  var position = $(this).position();
  $(this).animate({
    left: whereTo
  }, {
    duration: requestedDuration,
    start: function() {$('.silly').toggle(shouldHide);},
    complete: function() {
      $(this).toggle(!shouldHide);
    }
  });
});

$('.myanimate').on('click', function() {
  console.log('moving');
  $(this).trigger('slidehide', [750, 510, true]);
});
// Just for restarting or seeing again
$(document).on('click', '.silly', function() {
  console.log('restart');
  $('.myanimate').show().trigger('slidehide', [750, 10, false]);;
});
.myanimate {
  position: absolute;
  left: 100px;
}

.silly {
  display: none;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="myanimate">Greetings! (Click to trigger)</div>
<div class='silly'>Animation finished. (Click to restart)</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

Node.js setInterval is a method used to repeatedly execute a function

I have a code snippet for an http request that is supposed to run every one minute. However, I am encountering an issue with the following error: "Error: listen EADDRINUSE". Here is my current code: var express = require("express"); var app = express(); v ...

employ varying XSL stylesheets to display an XML document in a separate window

My issue involves an XML file being transformed by a specific XSL file (XSLT 1.0), which in turn includes multiple other XSL files with various templates. The challenge is to add a button to the rendered XML that, when clicked, opens the same XML in a ...

Tips for patiently waiting for an axios request to finish

Within my vuejs application, I am faced with the challenge of initializing an object using data retrieved from an ajax call: let settings = {} api.readConfig().then((config) => { settings = { userStore: new Oidc.WebStorageStateStore(), author ...

`Why won't the checkbox uncheck when the dropdown is changed in jQuery?`

I have a roster of users, each with a unique checkbox for selection. When I adjust the dropdown menu, a new group of users is chosen and marked as selected. However, I am struggling to uncheck the previously selected checkboxes based on the last dropdown c ...

Stop Code Execution || Lock Screen

Is there a way to address the "challenge" I'm facing? I'm an avid gamer who enjoys customizing my game using JavaScript/jQuery with Greasemonkey/Firefox. There are numerous scripts that alter the DOM and input values. In my custom script, I hav ...

Display a label upon hovering over an image

Is there a way to create an effect where upon hovering over an image, a pop-up image is displayed like this: https://i.sstatic.net/OloUH.png Any suggestions on how I can achieve this using HTML and CSS? Thanks in advance! ...

The response from the Ajax request in jQuery did not contain any content to download

I have a PHP script that generates PDF output successfully when accessed directly. Now, I want to fetch this PDF file using AJAX. In pure JavaScript, the following code snippet works well: var req = new XMLHttpRequest(); req.open("POST", "./api/pd ...

Troubleshooting Database Saving Problem with Vue.js and Ruby on Rails

Trying to configure a nested form with Vue.js in a Rails application to save ingredients for a recipe. While all other details of the ingredients are saving correctly, the ingredient name (from an input field) is not getting saved in the database. How can ...

Having trouble with getting the background image URL to work in Django CSS?

Hey there, I'm having an issue with my header-task class. The background-image doesn't seem to be showing up, even though when I click the URL in Visual Studio Code, the image displays. Can anyone help me figure out what's going wrong with m ...

Issue with NextJs function not receiving the specified argument variable

Currently, I am focused on developing a Shopify website and fine-tuning the functionality of the shopping cart. My onClick event triggers a function that initiates the process of adding items to the cart. The first step involves checking if there is an exi ...

Fetching an item from Local Storage in Angular 8

In my local storage, I have some data stored in a unique format. When I try to retrieve the data using localStorage.getItem('id');, it returns undefined. The issue lies in the way the data is stored within localStorage - it's structured as a ...

How can I pass an array from HTML to Node.js and subsequently store it in MongoDB?

Looking to combine the values of longitude and latitude into one array for input, then store it in the database. While there are plenty of examples on handling arrays, most of them are based on PHP. Check out the following code snippet: HTML <html> ...

Issue with KeyboardDatePicker in Material-UI/Pickers occurs when InputAdornmentProps property with position start is added, leading to an unexpected margin

I am currently working with a component from material-ui/pickers and this is the code snippet: <KeyboardDatePicker value={selectedDate} onChange={(_, newValue) => handleClick(newValue)} labelFunc={renderLabel} disableToolbar variant=&a ...

problem with nivo slider causing content to overflow

My webpage is using nivoslider to display images. However, I am facing an issue where the images are overflowing one by one until the page fully loads. I have tried setting the overflow:hidden property in the CSS but it doesn't seem to correct the pro ...

Reordering items in Angular2 ngFor without having to recreate them

I am facing a unique situation where I must store state within item components (specifically, canvas elements) that are generated through an ngFor loop. Within my list component, I have an array of string ids and I must create a canvas element for each id ...

Replicate a click using jQuery to retrieve a filtered multigallery based on the URL

I have a website that was built using Elementor for a photographer. The site features an Elementor Multigallery with a filter at the top. I am looking to create external links that will direct users to specific subpages showing only filtered items. For ex ...

Interactive multi-phase form with field populated by jQuery

Having an issue with a script that fills an input field when the value is less than 4. Unfortunately, when the value is less than 4, the script fills the field but doesn't select the value. This causes a problem when moving to the next step as there i ...

Ensuring Proper Alignment of Headers in CSS

I'm struggling to align my header correctly. Despite getting close in Internet Explorer, it looks terrible in Firefox with the code below. I've scoured forums for solutions but the more I try to fix it, the worse it looks. All I want is for heade ...

The shared module for next/router is not found in the shared scope default within Next.js and @module-federation/nextjs-mf

I am working on a JavaScript Turbo repo with a host app that has the following configuration in its next.config.js: const { NextFederationPlugin } = require("@module-federation/nextjs-mf"); const nextConfig = { reactStrictMode: true, ...

Flexible columns with dynamic maximum width based on percentage

After extensive research, I am turning to stackoverflow for help with a seemingly simple task that has proven difficult to achieve. I have three columns of expandable content and need them to adjust in size proportionally when one or more are expanded. Eac ...