Looking for solutions for handling sliding animations in jQuery?

I have a script that creates a sliding effect with a list of items. When you click on a list item, a box slides to the right, and clicking again will slide it back to its original position in a toggle fashion.

Check out the demo here:

The issue I'm facing is regarding the width of the panel during the slide-out animation. I want the panel's width to be 700px as it slides out.

$(".panel").css("width","700px");

During the slide back in animation, I want the width to be 350px so that it hides behind the list again.

$(".panel").css("width","350px");

However, the problem I'm encountering is that when it slides back, the panel doesn't fully hide behind the list and still shows on the right side. Any help would be greatly appreciated. Thank you!

Answer №1

Hello there, I took the liberty of making some assumptions about your overall goal, and I believe this might be what you were aiming for. Here are the key changes I made:

    <script type="text/javascript>
    $(document).ready(function() {

      $('.block').click(function(){
        var id= $(this).attr('id');
        var data_id= $(".data").html();
        var panelPositionLeft=$('.panel').css('left');

        if(panelPositionLeft=='0px') {
          //the .panel is hidden, so slide it out and populate .data with the new id
          $('.panel').animate({left: 350, width:700});
          $('.data').html(id);
        } else if (data_id!=id){
          //something other than the previous .block was clicked and the .panel is obviously open, so don't collapse, just add the new id into .data
          $('.data').html(id);
        } else {
          //neither of the previous situations are true, so it must be that the previously clicked block is being clicked again. Just slide it closed and don't change the value of .data
          $('.panel').animate({left: 0, width: 350});       
        }
      });


      $('.close').click(function(){
        // just slide it closed.
        $('.panel').animate({left: 0, width: 350});
      });

    });

    </script>

While there are still some areas for improvement, I hope this version is easier to comprehend. Feel free to give it a try and let me know if I misunderstood the issue.

Thank you!

Answer №2

One possible solution is to encase the "+" with single or double quotes, such as "+" + panel.outerWidth(). Give it a try and see if that resolves the issue.

Sincerely, Richard

Answer №3

Just a note for future reference: here is my take on the solution presented by masondesu. While it bears a striking resemblance, I have included if statements that may not be entirely necessary (unlike in masondesu's version).

    $(document).ready(function () {
        $('.block').click(function () {
            var id = $(this).attr('id');
            var data_id = $(".data").html();
            var panel = $('.panel');
            var panel_width = $('.panel').css('left');
            var currLeft = panel.css('left');
            var blockWidth = $(".left").outerWidth();
            if (data_id == id) {
                if (currLeft == "0px") {
                    panel.animate({ left: blockWidth, width: "700px" });
                } else {
                    panel.animate({ left: "0px", width: "350px" });
                }
            }
            else {
                if (currLeft == "0px") {
                    panel.animate({ left: blockWidth, width: "700px" });
                } else {
                    panel.animate({ left: "0px", width: "350px" });
                }
            }
            $('.data').html(id);
            return false;
        });
        $('.close').click(function () {
            var panel = $('.panel');
            var currLeft = panel.css('left');
            if (currLeft == "0px") {
                panel.animate({ left: blockWidth, width: "700px" });
            } else {
                panel.animate({ left: "0px", width: "350px" });
            }
            return false;
        });
    });

Sincerely,

Richard

Answer №4

Panel resizing is triggered only when you click on ".close" and not when you click on "li". As a result, the panel will not resize unless you specifically click on ".close".

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

Is it possible for my OAuth2 callback page to share the same HTML page? Also, what is the process for obtaining the token?

In my setup, I am working with static html and javascript along with C# Web API. One of the scenarios I encountered involves a link that triggers an oauth2 server from my HTML file named index.html. The question arises: Is it appropriate to establish the c ...

Can someone explain what {...props} means within the context of React Navigation's Stack.Screen?

Can you explain the importance of using {...props} on this specific page? <Stack.Screen name="Home"> {props => <HomeScreen {...props} extraData={someData} />} </Stack.Screen> Interestingly, my application functions correctly even w ...

Attempting to set up Prettier in my VSCode environment

I've been delving into JavaScript with the guidance of "Morten Rand-Hendriksen" on LinkedIn Learning. The instructor emphasized the importance of installing "Prettier" in our VSCode environment. Following his instructions, I headed to the "Extensions" ...

Adjusting the quantity of buttons in real-time following an ajax request

Creating buttons dynamically in an Ajax success function can be a challenge when the number of buttons varies each time. I am able to create the buttons, but since the exact number is unknown, adding the correct number of button listeners becomes tricky. ...

Access previous or following images seamlessly without the need to refresh the page

For my latest project, I am constructing a straightforward gallery system utilizing PHP and MySQL as the primary technologies. A key requirement of this system is the ability to navigate through images using the keyboard arrow keys. The challenge is to se ...

Looking for subsequence in dropdown choices with no assigned values

I need assistance with searching for a specific substring within text that is fetched from options generated by MySQL. How can I retrieve the selected option's text value in order to search for my desired substring? $(document).ready(function() { ...

Unraveling Vue Async Components - Harnessing the power of emitted events to resolve

I am looking to create a Vue async component that stays in a loading state until a custom event is triggered. This means it will render a specified loading component until the event occurs. Here's an example of how I want it to work: const AsyncComp ...

The Bootstrap 4 alpha 6 navigation bar is not being rendered properly on Google Chrome

Do you have a moment to check out this issue? It seems to be specific to Google Chrome. https://example.com/ Here is a snapshot of the problem: https://example.com/screenshot.png Take a look at the code snippet: <div class="collapse navbar-collapse ...

Setting a default value for an empty array in Joi

Struggling with the syntax to set a default value for an empty or missing array key. Joi.object({ items: Joi.array().empty([]).items(Joi.number()).default([42]), }) { items: [] } or { } In both scenarios, I want the default value of [42] to fill ...

Why does modifying a variable within the fetch URL result in undefined

I currently have a server running on the URL http://localhost:3000/. Within my JavaScript code, I have defined a variable called productCode with the value 'example-code55'. let productCode = 'example-code55'; const fetchData = async ...

Create an intricate table design using CSS grid and incorporate nested vue v-for loops for dynamic content rendering

I have data that is nested and I want to display it in a tabular format. Here is an example of the data; in the actual application, there could be dozens of entries in rows. <script> export default { name: 'Example', data () { retu ...

execute a series of asynchronous functions one after another

async function cancelUserSubscriptionHandler() { const unsubscribe = await fetch("/api/stripe-sessions/cancel-subscription", { method: "PATCH", body: JSON.stringify(), headers: { "Content-Type": "appli ...

Guide to animate/move a tile to a specified location using CSS at 90x90px dimensions

I am trying to achieve a smooth transition for grid[row1][col1] sliding over to grid[row2][col2], followed by an expansion to 90x90px Does anyone have any suggestions on how to accomplish this? Here is an example of the styling: <style type="text/css ...

A guide on applying color from an API response to the border-color property in an Angular application

When I fetch categoryColor from the API Response, I set border-left: 3px solid {{element.categoryColor}} in inline style. Everything is functioning correctly with no development issues; however, in Visual Studio, the file name appears red as shown in the i ...

jQuery highlight not working properly with versions 1.8.2 of jQuery and custom 1.8.24 of jQuery

Currently, I have the jQuery UI installed on my website with jquery 1.8.2 and jquery custom 1.8.24 versions. I cannot seem to figure out why the following code for a jQuery highlight effect is not functioning properly: $(document).ready(function () { ...

I have a query regarding the implementation of trackballcontrols.js in three.js

I'm trying to incorporate trackballcontrols.js into my project but I need to make some modifications. I'm having trouble understanding this code snippet, could you provide some explanation? var calculateMousePosition = ( function () { var v ...

Validate if a certain value exists within an array of data using NgIf

Is there a way to verify the existence of a value in an array of data? gjhg = [ id, name ] ...

Customize the appearance of the start and end dates using react-datepicker styling

Hey there, I could really use your assistance. I am currently working on a project that involves styling the startDate and endDate using the react-datepicker library. The image below shows what I aim to achieve: Dear Developers, your help is much apprecia ...

Can someone explain how I can effectively test the internal workings of a promise using Jasmine?

Within the Angular component I am testing, there is an async promise that I am struggling to examine. The code inside the 'then' block is crucial for my testing purposes, but I cannot seem to access it. angular.module('Ls', [ ]) funct ...

The Ajax request is not functioning as expected

Recently, I've been experimenting with AJAX for the first time and facing some challenges in getting it to work properly. In my view file (vueConsigne.php), I have a table that is generated by my controller. <tbody> <?php echo $tab_p ...