Animating several elements by toggling their classes

I'm struggling to implement smooth animations on this box. I've tried using 'switchClass' but can't seem to keep everything together. Any help would be greatly appreciated. Here is the code snippet for reference:

<script src="jquery.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<style>
#box {
    position: relative;
    margin: auto;
    padding: auto;
    display: block;
    width: 167px;
    height: 167px;
}
#box .item {
    position: relative;
    margin: 0;
    display: block;
    width: 100%;
    height: 33%;
    cursor: pointer;
}
#box .over {
    height: 84%;
}
#box .other {
    height: 8%;
}
#top {
    background: red;
}
#mid {
    background: green;
}
#bot {
    background: blue;
}
</style>
<script>
function animateBox(item) {
    $('.item').attr('class', 'item other');
    $('#' + item.id).attr('class', 'item over');
}

function resetBox() {
    $('.item').attr('class', 'item');
}
</script>
<div id='box' onmouseout="resetBox()">
    <div id='top' class='item' onmouseover='animateBox(this)'></div>
    <div id='mid' class='item' onmouseover='animateBox(this)'></div>
    <div id='bot' class='item' onmouseover='animateBox(this)'></div>
</div>

edit: The code is functioning correctly, however, some additional animations are needed to enhance the final output.

Answer №1

It might not be the most cutting-edge solution, but it gets the job done:

var $elements = $('.element').on({
    mouseover: function () {
        $elements.removeClass('active inactive');
        $elements.stop().filter(this).animate({height: '84%'}, function () {
            $(this).addClass('active');
        })
        .end().not(this).animate({height: '8%'}, function () {
            $(this).addClass('inactive');
        });
    },
    reset: function() {
        $elements.removeClass('active inactive').stop().animate({height: '33%'});
    }
});

$('#container').mouseout(function() {
    $elements.trigger('reset');
});

http://jsfiddle.net/dfsq/4vnkh/1/

Answer №2

If you're looking to add some animation effects, I recommend checking out the jQuery animate documentation

Here's an example of how you can achieve this:

$('.element').hover(function() {
 $('.element').animate({
    width: '50%'
  }, 500, function() {
    // Animation complete.
  });
}, function() {
  $('.element').animate({
    width: '100px'
  }, 500, function() {
    // Animation complete.
  });
});

In this scenario, using `mouseout` or `mouseover` isn't necessary.

Answer №3

If you're using CSS class attributes for your animation, why not take advantage of the CSS3 hover pseudo-selector?

For example:

.box {
    width: 200px;
}

.box:hover {
    width: 400px;
}

<div class="box">Hover over me!</div>

Additional: Reponse to feedback


If you need a custom animation duration, you can use a callback function with a specified duration. Here's how:

$('#div').animate({
   width: '200px',
   color: 'blue'
}, 5000, function() {
   // Animation completes after 5 seconds.
   alert("Animation complete!");
});

Addition #2


The issue lies here:

$('.item').attr('class', 'item other');

This causes each box to first become 8% height before expanding the main animating box. Removing this will keep your #box at a consistent height throughout all animations!

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

Axios encounters CORS issues, while fetch operates smoothly

After going through various questions on CORS errors to no avail, I am facing a dilemma in my NuxtJS client application. Whenever I try to make a simple POST request using axios, I encounter CORS issues. However, when I switch to using the fetch API, every ...

Creating dynamic JSX content in NextJS/JSX without relying on the use of dangerouslySetInnerHTML

I have a string that goes like "Foo #bar baz #fuzz". I'm looking to create a "Caption" component in NextJS where the hashtags become clickable links. Here's my current approach: import Link from "next/link"; const handleHashTag = str => st ...

Unable to Achieve Full Height with Vuetify Container

Challenge: I'm facing an issue with my <v-container> component not consistently spanning the entire height of the application. Despite trying various methods such as using the fill-height property, setting height: 100%;, height: 100vh;, and expe ...

Utilize HTML5, CSS, and Responsive Web Design to place four boxes into a div container

Is there a way to arrange four boxes inside a div so that they are positioned at the corners of the top-left, top-right, bottom-left, and bottom-right? And when you click on the box in the middle, a window opens with text. I'm looking for something s ...

JavaScript doesn't seem to be functioning properly within PHP

I have implemented the supersized jQuery script to incorporate sliding backgrounds on my WordPress page. Now, I aim to create unique slides for different sites and require a PHP if request. This is my code: <?php if ( is_page(array('Restaurant&a ...

Disabling `no-dupe-keys` in ESLint does not seem to be effective

Currently, I am working on a project where I have incorporated Typescript and ESLint. However, I have encountered an issue with the error message stating: An object literal cannot have multiple properties with the same name. I am looking to disable this s ...

My component is displaying a warning message that advises to provide a unique "key" prop for each child in a list during rendering

I need help resolving a warning in my react app: Warning: Each child in a list should have a unique "key" prop. Check the render method of `SettingRadioButtonGroup`. See https://reactjs.org/link/warning-keys for more information. at div ...

PHP encountered an issue while trying to compare the value stored in the $_POST variable with the value stored in a

In my current project, I have utilized a JSON file to store data and PHP to retrieve and display it. However, I am facing an issue when comparing values from $_POST - specifically, if the value contains spaces, the comparison fails. Here is the problematic ...

To successfully handle this file type in Next.js, make sure you have the necessary loader configured as no loaders are currently set up to process this specific file

I encountered an issue when trying to load an image from a local directory in my Next.js application Failed to compile ./pages/components/image.png 1:0 Module parse failed: Unexpected character '' (1:0) You may need an appropriate loader to hand ...

AngularJS and adding to an array in the routing process

I'm currently working on creating a contact list with two different views. One view displays all the contacts and includes an option to add a new contact, which is represented by a button rather than a space to input information directly. The other vi ...

Add a User Control to a webpage seamlessly without triggering a full page reload

Is there a way to incorporate a user control into my pages without causing page post backs? I am unable to utilize Update Panels due to the presence of file upload controls within the user controls. In addition, I prefer not to place custom controls in a ...

Press the key to navigate to a different page

I have an input field for a search box. I want it so that when I enter my search query and press enter, the page navigates to another page with the value of the input included in the URL as a query string. How can I achieve this functionality? Thank you ...

What is the proper way to showcase an element positioned absolutely within a Dialog window using material-ui?

My current project involves using React, TypeScript, StyledComponent, and MaterialUI. I am looking to add a button to a Dialog window (material-ui) similar to the design shown in this example image. However, when I apply position: absolute to the button, ...

Persistent button positioned at the bottom of the page, remaining visible even when scrolling to the very end of the content

I am looking to add a floating button that remains in the same position relative to the content until the window is scrolled to a certain point, after which it sticks to the end of the content. In simple terms, I want the element to act as 'relative& ...

Renew Firebase Token

Currently, my email and password authentication flow in web Firebase JavaScript involves generating a token that I then verify on my node.js backend using firebase-admin. To make things easier, I store this generated token in the browser's local/sessi ...

Schema-specific conditions for JSON data

I have been experimenting with the if-then-else statement in JSON, but I am encountering some issues with it. { "type": "object", "minProperties": 2, "maxProperties": 2, "properties": { "human": { "enum": [ "Kids", "Ad ...

Ajax calls within nested functions are not being executed in the correct sequence

Currently, I am utilizing the geonames API to retrieve geographical information. My objective is to extract the names of states within a country using the getStateInfo function and subsequently obtain a list of cities in each state through the getCityInfo ...

Yet another query about jQuery validation

I need help validating the promoRent field to ensure it contains a number. While this field is not required, if a value is entered, it must be greater than lotRent. Here's the current code snippet: jQuery.validator.addMethod("PRgreaterThanLotRent", ...

Encountering issues while trying to duplicate react-table CodeSandbox: API error when using localhost

Trying to implement this CodeSandbox project into my own project has been challenging. On navigating to the Example component, a 404 error pops up: Error: Request failed with status code 404. The API is targeting this endpoint: http://localhost:3000/api/pr ...

Python: Mimicking Splinter/Selenium Functionality to Test a JavaScript-Driven Website

My automated bot interacts with a dynamic website using Splinter and Selenium. Despite its effectiveness most of the time, it occasionally encounters exceptions due to random events. Debugging these occurrences is quite challenging, especially since the we ...