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

Could the addition of iframes enhance the efficiency of websites containing a vast amount of DOM elements?

When dealing with websites that have a massive amount of DOM elements, could there be any performance advantages to displaying some content within an iframe? For instance, the project I am currently involved in features a large HTML-based tree structure ...

Maximizing the performance of plotting hundreds or thousands of series in a 2D scatter or line chart using Echarts

Plotting a large data set with hundreds or thousands of series using Echarts has proven to be slow and challenging to manage. If you take a look at the example code provided in this large and progressive options on single series instead of all plotted se ...

How can I make the expired date display in red color in a JavaScript date property?

In my HTML, I have 4 different dates. The expired date "END MAR 20" should be displayed in red color instead of green. The next date, "END APR 29," should be in green color. All preceding dates should also be displayed in red. I have successfully filtered ...

Issue with JQuery causing maxlength input not to work

Is there a way to use JQuery to set the maxlength attribute for an input[type='text'] while users are typing, so that once the max value is reached, input will stop? This is the code I have been trying: $(document).ready(function(){ $(&apos ...

Is it possible to direct users to varying links based on their individual status?

import React from "react"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import Link from "next/link"; import { cn } from "@/lib/utils"; import { FaCircleChec ...

Enhance text by hovering over it

I am currently working on implementing a unique feature using jQuery and CSS. Rather than just inheriting the width, I want to create a magic line that extends to the next index item. Scenario: 1: Hover over Element one ELEMENT ONE ELEMENT TWO ELEM ...

Unable to switch checkbox state is not working in Material UI React

I am experiencing an issue with the Material UI checkbox component. Although I am able to toggle the state onCheck in the console, the check mark does not actually toggle in the UI. What could be causing this discrepancy? class CheckboxInteractivity exten ...

What is the significance of the any type in Typescript?

As I delve into learning Typescript, a question arises in my mind. I find myself pondering the purpose of the any type. It seems redundant to specify it when every variable essentially acts as an "any" type by default. Consider this scenario where the out ...

How to eliminate a particular item within a string only in rows that include a different specific item using JavaScript

Is my question clear? Here's an example to illustrate: let string = "Test text ab/c test Test t/est ### Test/ Test t/test Test test" I want to remove / only from the line that includes ###, like so: Test text ab/c test Test t/est ### Test T ...

Utilize custom {tags} for replacing strings in a CSS file using str_replace in PHP

My code consists of a script that updates a CSS file based on user input from an html form. The script executes a str_replace function, scanning the CSS file for specific "tags". For example: html,body { background: {bgcolor} url(../images/bg.jpg) re ...

Employing jQuery to extract the text from the h4 class="ng-binding" element beyond the Angular scope

Is it possible to retrieve the current text content of <h4 class="ng-binding"></h4>? The text content is generated dynamically within the angular.js setup. I am interested in finding a way to extract this text using jQuery or JavaScript from ...

Button for AngularJS delete request

I have developed a live polling application that allows users to create, view, and delete questions from the table pools stored in the RethinkDB database. The issue lies with the delete functionality. While sending a DELETE request using POSTMAN successfu ...

When I attempt to connect to my local MongoDB database, including a specific port in the URI is preventing the connection from being

While testing a connection to a local DB using mongoose and mongodb, I encountered an issue. Whenever I include a port number in the URI passed to mongoose.connect(), I receive a connection refused error. async function connectDB() { const db = await m ...

Calculate the sum of the elements within an array that possess a distinct attribute

I need to calculate the sum of certain elements in an array. For example, let's consider this array: var sampleArray = [ {"id": 1, "value": 50, "active": true}, {"id": 2, "value": 70, "active": false}, ...

How to display and retrieve data from a JSON object using JavaScript

Having trouble retrieving input values from a JSON object and getting 'undefined' when running the code. Any suggestions or ideas would be greatly appreciated as I have tried various approaches. Additionally, I need to utilize JSON for my school ...

The "as" property in NextJS Link does not properly reload the page when opened

I recently started using NextJS and I have a question about its router. I want to link to a page, but I would like the URL to be different. <Link href="/About/About" as="/about-page"> <a> Who We Are <im ...

How to store angular 2 table information generated using ngFor

I am currently working on a project where I need to create an editable table using data retrieved from the back end. My goal now is to save any updated data. I attempted to use formControl, but it seems to only save the data in the last column. Below is a ...

Discover the smallest and largest values within the multi-layered object

My JavaScript object is deeply nested with an infinite number of children, each containing a value. var object = { value: 1, children: { value: 10, children:{ value: 2, children: {...} } } } I've tried ...

What is the reason behind Selenium not utilizing JavaScript?

I've been a beginner in the world of Javascript for a while now, with my main goal being to use it for creating Selenium automations as part of my journey into QA automation. However, I find myself quite perplexed when it comes to the language. In al ...

Issue with ASP.NET Base64 image source rendering incorrectly

After retrieving a Base64 string from Azure active directory using a Lambda function, which represents a user's profile picture, I am facing issues displaying it on an ASP.NET page. Below is the code snippet in ASP.NET (The referenced HTML object is ...