Unable to make jQuery animate top function work

I have three rectangles set up like this. I've managed to make them disappear when clicking the close button on the right side of each rectangle, but I'm struggling with getting the remaining rectangles to move upward to fill the empty space. Here's the code I've tried so far:

$(".note-content-right").click(function() {
  $(this).parent().removeClass("note-float-view");
  var thisDataIndex = $(this).parent().attr("data-index");
  $(".note-float").each(function() {
    if(($(this).hasClass("note-float-view")) && ($(this).attr("data-index") > thisDataIndex)) {
      $(this).animate({
        "top" : "-=54px"
      });
    };
  });
});

Unfortunately, it's not working as expected.

If anyone can provide some assistance, that would be greatly appreciated! :)

$(document).ready(function() {
  $(".note-float").removeClass("note-under");
  loadNote();
});

function loadNote() {
  $(".note-float").each(function(index) {
    var el = $(this); 
    setTimeout(function () {
      el.addClass("note-float-view");
    }, index * 200);
  });
}

function unloadNote() {
  $(".note-float-view").each(function(index) {
    var el = $(this); 
    setTimeout(function () {
      el.removeClass("note-float-view");
    }, index * 200);
  });
}

$(".note-content-right").click(function() {
  $(this).parent().removeClass("note-float-view");
  var thisDataIndex = $(this).parent().attr("data-index");
  $(".note-float").each(function() {
    if(($(this).hasClass("note-float-view")) && ($(this).attr("data-index") > thisDataIndex)) {
      $(this).animate({
        "top" : "-=54px"
      });
    };
  });
});

$(".load-note").click(function() {
  $(".note-float").removeClass("note-under");
  $(".note-float").removeClass("note-float-view");
  setTimeout(function() {
    loadNote();
  }, 500);
});
.note-float-view {
  top: 24px !important;
  opacity: 1 !important;
  transition: top 1s, margin-bottom 1s, opacity 1s;
}

(note styles and classes here)

</script>

Answer №1

The styling of .note-float-view with top: 24px !important; is causing a conflict with the animation. Removing the !important declaration resolves this issue.

In addition, I have made modifications to the 'reset' function to ensure that all items return to a top position of 24px instead of wherever the animation may have left them. It might be more effective to handle this adjustment on individual items at the conclusion of the animation process.

$(document).ready(function() {
  $(".note-float").removeClass("note-under");
  loadNote();
});

function loadNote() {
  $(".note-float").each(function(index) {
    var el = $(this);
    setTimeout(function() {
      el.addClass("note-float-view");
    }, index * 200);
  });
}

function unloadNote() {
  $(".note-float-view").each(function(index) {
    var el = $(this);
    setTimeout(function() {
      el.removeClass("note-float-view");
    }, index * 200);
  });
}

$(".note-content-right").click(function() {
  $(this).parent().removeClass("note-float-view");
  var thisDataIndex = $(this).parent().attr("data-index");
  $(".note-float").each(function() {
  if (($(this).hasClass("note-float-view")) && ($(this).attr("data-index") > thisDataIndex)) {
    $(this).animate({
     "top": "-=54px"
   });
 };
});

$(".load-note").click(function() {
  $(".note-float")
    .removeClass("note-under")
    .removeClass("note-float-view")
    .css("top","24px");

  setTimeout(function() {
    loadNote();
  }, 500);
});
.note-float-view {
  top: 24px ;
  opacity: 1 !important;
  transition: top 1s, margin-bottom 1s, opacity 1s;
}

/* Additional CSS styles included here for reference... */

@media (max-width: 575px) {
 /* Responsive CSS styles added here */
}
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.11/css/all.css" integrity="sha384-p2jx59pefphTFIpeqCcISO9MdVfIm4pNnsL08A6v5vaQc4owkQqxMV8kg4Yvhaw/" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,700,700i" rel="stylesheet">

<div class="note-wrapper">


  <div class="note note-float success" data-index="1">
    <div class="note-content-left">
      <i class="fas fa-check-circle"></i>
    </div>
    <div class="note-content-center">
      You have successfully added <b>1 item(s)</b>
    </div>
    <div class="note-content-right">
      <i class="fas fa-times close-success"></i>
    </div>
  </div>

  /* More HTML content for different types of notes... */

  <div class="load-btn-wrapper">
    <a class="button white-btn footer-btn load-note">Reload </a>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

A point to consider is that using a fixed pixel value like 54px for animating position may cause layout issues when text wraps across lines. It's advisable to calculate the height dynamically and animate based on that to avoid such problems. Avoid hardcoded pixel values and reliance on absolute positioning as much as possible, as they can lead to manual adjustments like in this case. For smoother transitions, leveraging document flow and avoiding absolute positioning can simplify your workflow. One alternative approach could be animating max-height to zero with hidden overflow-y to remove elements without needing manual repositioning.

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

Turn off automatic HTML correction in Google Chrome

I'm currently developing a NODE.js app that utilizes Nunjucks as its view engine. To ensure the validity of the HTML being generated, I've implemented tests to check if all tags are properly closed. My approach involves spinning up the applicatio ...

Update the div without altering its contents

Hello, I have a webpage where I am utilizing multiple select lists sourced from 4 different XML files. There is a function that updates one specific div by loading an XML file using the PHP command "$scripts = simplexml_load_file($link);" and then applies ...

What is the best way to add borders to the cities on interactive SVG maps?

I'm currently developing Interactive SVG Maps showcasing Turkey. The map consists of 81 cities, each represented by <g> elements, and their respective districts, created as child elements within the city elements. It's worth noting that the ...

"Yakov's slender typefaces are appearing incorrectly on the screen

I recently tried to incorporate Yakov thin fonts using CSS @font-face, but I noticed that the fonts appear quite different from the original ones. Any idea why this might be happening? Below is the code snippet I used: @font-face { font-family:' ...

Unable to output the string using htmlspecialchars

Oops! I made a mistake... just came across a JavaScript alert box! I just included htmlspecialchars. $src = './imgs/flag.jpg'; echo sprintf("<img alt=\"'.htmlspecialchars($name).'\" src=\"%s\" />", $src); I ...

Input information into a JSON container

I've been struggling to find a solution for this issue. Here's the JSON variable I'm working with, which includes the names "rocky" and "jhon": var names = [ "rocky", "jhon" ]; Now, I need to add a new val ...

Pure CSS text slideshow

I'm currently working on developing a text content slideshow using only CSS. Here is the HTML/CSS code I have: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>CSS text slideshow examp ...

What methods are available to verify all my (JavaScript) AJAX calls when they are being sent to Node.js?

My web app sends hundreds of HTTP requests to a Node.js API I created. I need to ensure that only authenticated requests are accepted by Node.js. The issue at hand: I don't want to manually update each AJAX request in my JavaScript code to include a ...

Running a continuous JQuery function loop

I need assistance with creating a continuous image fade in and out effect. Currently, my code looks like this: $(document).ready(function(){ $(".slider#1").delay(1000).fadeIn(2000); $(".slider#1").delay(1000).fadeOut(2000); $(".sli ...

Discovering a specific element using jQuery

I am trying to work with a div structure like this: <div class="country"> <div class="cty_popover"> <p>TITLE</p> <ul> <li>NAME 1</li> <li>NAME 2</li> ...

Issue with transforming rotation in Quirks mode

Currently, I'm developing a website in quirks mode which does not allow the use of . In my project, I am facing an issue where CSS3 translate image is not working in IE10 and 11, although it works fine in IE9 due to the limitations mentioned above. Is ...

The PHP script to modify a MySQL database fails to make any updates

I am having an issue with my code for updating a MySQL database. The code runs without errors, but when I check the records in phpMyAdmin, the database is not being updated. Can someone please assist me with this? $database = "carzilla"; $con = mysql_c ...

Implementing user-driven filtering in a React table

When a user clicks on the submit button, data will be loaded. If no filter is applied, all data will be displayed. const submit = async (e: SyntheticEvent) => { e.preventDefault(); const param = { ...(certificateNo && ...

Tips for transforming an html form into an ajax request for a rest controller when dealing with a multi-select field

I am encountering an issue with the field "roles" as it is a select list with multiple choices. I need to convert this field into an array, but I have not been able to find any information on how to do so. Any assistance would be greatly appreciated. Thi ...

Tap on the HTML5 video to exit the fullscreen mode

Objective I have successfully implemented a fullscreen video setup that triggers when a link is tapped on a mobile device. To maintain a clean aesthetic, I have hidden the HTML5 video controls using CSS. The desired functionality includes closing the full ...

The success function in AJax does not properly execute on Safari browsers

Here is an example of my AJAX function: $.ajax({ url: "thankyou", type: "POST", data: arr, tryCount : 0, retryLimit : 3, success: function(response) { if(response == "Success"){ location.href = "/thankyou.html"; }else{console.l ...

The completion action is never carried out

I am currently facing an issue with one of my JavaScript functions. I have several $.ajax calls throughout my webpage followed by .done(), and they all seem to be functioning properly, except for one. Can anyone identify what could be causing the error? m ...

Displaying image titles when the source image cannot be located with the help of JavaScript or jQuery

I am currently facing an issue where I need to display the image title when the image is broken or cannot be found in the specified path. At the moment, I only have the options to either hide the image completely or replace it with a default image. $(&apo ...

Can JavaScript be used to dynamically update drop down lists in a gridview?

My gridview has multiple fields including PreviousPoints, GainedPoints, and TotalPoints. In edit mode, PreviousPoints is not editable, GainedPoints is a dropdown list, and TotalPoints is also a dropdown list. Whenever the selected value in GainedPoints ch ...

Transfer data in an array within value="" separated by ':' through AJAX/JSON in PHP and HTML

Can data be passed in array form using AJAX/JSON? For example, like ".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."? Here is a sample code snippet to illustrate this: if(sqlsrv_num_rows($query) > 0 ...