An easy way to switch animations using CSS display:none

Dealing with some missing gaps here, hoping to connect the dots and figure this out.

I'm attempting to create a functionality where a div slides in and out of view each time a button is clicked. Eventually, I want multiple divs to slide out simultaneously. Currently using:

//css
display {visibility:hidden}

Then checking for:

//js$
("#initiate").click( function(event) {
$("#initiate").click( function(event) {
  if ($("#nav").is(":hidden")) {
    $("#nav").stop().animate({
      right: '520px'
    }, 1300);
            }
    else {
      $("#nav").stop().animate({
        right: '320px'
      }, 1300);
    }

  });

Facing a few issues: 1. Slide only works when visibility is set to something other than "none." 2. Only slides out, doesn't slide back in.

Any suggestions on how I can get this working?

http://jsfiddle.net/c48vdqf6/2/

Answer №1

Animating the display property can be tricky since CSS does not allow it. One common challenge for developers is trying to animate this property.

To work around this limitation, you can animate the right property instead. By positioning the element off-screen and animating it to slide into view when needed, as shown in your Fiddle example.

EDIT

Regarding the issue where the element only slides out but not back in, you can use a class to control its position dynamically:

$("#initiate").click(function(event) {
    if ($("#nav").hasClass("hidden")) {
        $("#nav").stop().animate({
            right: '-320px'
        }, 1300);

    } else {
        $("#nav").stop().animate({
            right: '520px'
        }, 1300);
    }
    $("#nav").toggleClass("hidden")
});

Check out the updated Fiddle for reference.

I hope this explanation helps!

Answer №2

My preferred method involves using CSS3 for animation with transitions, and then utilizing JavaScript/jQuery to toggle classes:

https://example.com/jsbin-animation

<!DOCTYPE html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
<style>
#display{
  width:300px;
  height:100vh;
  position:fixed;
  top:0;
  right:0;
  background-color:black;
  transition:right 0.5s ease;
}
#display.hide{
  right:-300px;
}
</style>
</head>
<body>
<p id="initiate">test</p>
<div id="display" class="hide"></div>
<script>
$("#initiate").on("click",function(){
 $("#display").toggleClass("hide");
});
</script>
</body>
</html>

This approach reduces code complexity and simplifies maintenance in the long term, especially when dealing with multiple sliding div elements.

Answer №3

Instead of constantly checking if the element is visible, it's more efficient to use a class or flag to determine its position.

$("#start").click(function(event) {
    if ($("#menu").hasClass("inactive")) {
        $("#menu").stop().animate({
            left: '-300px'
        }, 1000);
    } else {
        $("#menu").stop().animate({
            left: '500px'
        }, 1000);
    }
    $("#menu").toggleClass("inactive");
});

FIDDLE

Answer №4

I decided to switch up the font color and make some modifications to the if statement for a more advanced approach. $("#activate").click( function(event) {

http://jsfiddle.net/c48vdqf6/3/

if ($("#menu").css('left') == "280px") {
  $("#menu").stop().animate({
    left: '-280px'
  }, 1200);
}
else {
  $("#menu").stop().animate({
    left: '280px'
  }, 1200);
}
});

Answer №5

If I were to tackle this task, I would utilize CSS over Javascript and then employ Javascript to dynamically add and remove a class called 'show' or something similar. A similar approach was used by me recently for an off-canvas menu.

For your reference, I have provided an example here...

https://jsfiddle.net/wyd1rxhg/

.menu {
  transition: left 0.5s ease;
  position: absolute;
  width: 400px;
  left: -400px;
  background-color: red;
}

.show {
  left: 0;
}

To make it slide back in, simply remove the show class and watch it disappear!

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

Does the default input default to text format?

I have a somewhat peculiar question. I'm currently experimenting with Javascript for a plugin and came across an interesting scenario. Let's say I have an input element that is structured like this: <input type='cc' id='cc&apo ...

aligning columns within a flexible element that has a maximum height

Within this flex element, I have set flex: column wrap; and max-height: 150px;. The issue I'm facing is that justify-content doesn't seem to be working. However, when I switch to using height: 150px, the alignment works fine. This problem arises ...

Validation for dates in Angular.Js input is important to ensure that only

Take a look at this form: <form name="user_submission" novalidate="novalidate" method="post"> <input type="date" name="date_of_birth" ng-focus="save_data()" ng-model-options="{timezone: 'UTC'}" ng-pattern="/^(19\d{2}|[2-9]& ...

What is the most effective way to showcase a list of image URLs in HTML with Vue?

Currently, I am working with an array called thumbnails that holds the paths to various images. My goal is to use masonry in Vue to arrange these images in a grid format, but I'm encountering some difficulties achieving the desired outcome. This is m ...

Tips for uploading a file with fetch

While I know this question has been asked before, none of the solutions seem to be working for me. Initially, I attempted to resolve the issue using axios, but it appears that there is a bug preventing me from utilizing it for file uploads. Therefore, I am ...

How can I ensure that the state is only updated after the map function has finished executing in React?

I am encountering an issue with updating the state after mapping over an array of ids using an async function. The goal is to store the result in newArr and then update the state via setState. However, the state is being updated before the mapping operatio ...

How does the PhoneGap API handle Timestamp format?

Within the realm of app development, phoneGap offers two vital APIs: Geo-location and Accelerometer. Both these APIs provide a timestamp in their onSuccess method. In Accelerometer, the timestamp appears as '1386115200', whereas in Geo-location i ...

Regular expressions or regex can be used to match the initial letter or letters of various words

Struggling with regex? After searching for an hour, the best solution found was this one. Still unable to crack it though... Here's what I need: Have a JS array that needs to be filtered. The array looks like: [ 'Gurken halbiert 2kg', &a ...

Please ensure all three of the last checkboxes are ticked before finalizing submission

Here is the list of checkboxes for my PHP form. I am trying to figure out how to write a script that will only allow the form to be submitted if the last three checkboxes are checked. I have tried looking at similar questions but haven't found the sol ...

Top recommendations for implementing private/authentication routes in NextJS 13

When working with routes affected by a user's authentication status in NextJS 13, what is the most effective approach? I have two specific scenarios that I'm unsure about implementing: What is the best method for redirecting an unauthenticated ...

JavaScript CheckBox Color Change Not Functioning

Hello, I am currently experimenting with the checkAll function. When I click on the checkAll checkbox, it should select all rows and change their background color accordingly. Below is the JavaScript code I am using: function checkAll(objRef) { v ...

Incorporating nested maps in JSX for efficient data manipulation

{normalizedData.map(item => <div key={item.display_date_numberic}> <div>{item.display_date_numberic}</div> </div> {!isEmpty(item.applicants) && item.applicants.map(applicant => <div className= ...

The dimensions of the window - creating divs within td elements - the appearance of scroll

Here is the HTML code that I am working with: <table> <tr> <td class='tclone' id='clone'></td> <td class='loader' id='loader'> <div id='tdiv& ...

Navigation through dots on a single page

Having an issue with my dot navigation and anchor links placement. I want the anchors to be vertically centered in the middle of the section, regardless of window size. Here's what I'm aiming for : For larger windows : And for smaller windows : ...

Discovering the most concise string within the array

I've been working on a JavaScript program function that is supposed to return the smallest string in an array, but I keep encountering an error whenever I run it. Below is the code I have written: function findShortestWordAmongMixedElements(arr) { ...

Sending jQuery events from an aspx page to an ascx control

Yesterday, I began utilizing ascx and started breaking down my "dynamic" default.aspx page into smaller segments. In default.aspx, there is a significant amount of JavaScript/jquery code responsible for managing various events. After moving some html code ...

I'm having trouble with using setInterval() or the increment operator (i+=) while drawing on a canvas in Javascript. Can anyone help me out? I'm new

I am looking to create an animation where a square's stroke is drawn starting from the clicked position on a canvas. Currently, I am facing an issue where the values of variables p & q are not updating as expected when drawing the square at the click ...

Refresh the table following the removal of an item

I am currently working on displaying server data in a table. The delete function is functioning properly, but the deleted item only disappears from the table after refreshing the page. Is there a way to trigger a re-render of the component after deleting a ...

Vue js lacks the ability to effectively link HTML elements to corresponding JavaScript functions

I seem to be missing a crucial element in my spring boot application. I am attempting to follow the initial steps outlined in the Vue documentation to create the most basic Vue application possible. Here is what I currently have: @Controller public class ...

Tips for checking the validity of PHP variable names, such as $as['abc'], within an HTML textbox

Can anyone assist me with validating a user input PHP variable name such as $as_cap['abc'] during insertion? I need to verify if the format of the variable name is correct or incorrect. Currently, I am using eregi("^[a-z0-9_.'-]{1,50}$") ...