Using jQuery to create a flawless animation

I am currently working on an animation project, and I have shared my progress on jsfiddle. Below is the code snippet I have utilized:

/*  JavaScript:  */

    var app = function () {
        var self = this;
    
        var allBoxes = $('.box');
        var shadow = $('#shadow');
        var busy = false;
    
        self.init = function () {
            self.events();
        };
    
        self.getBoxLeftPosition = function(id)
        {
            var left = 100;
    
            if (id == 'box2')
            {
                left = 300;
            } else if (id == 'box3')
            {
                left = 500;
            } else if (id == 'box4')
            {
                left = 700;
            }
    
            return left;
        };
    
        // rest of the code continues...
        

My goal with this project is to create an interactive animation where hovering over one of the four boxes causes it to expand slightly while graying out the others. When the mouse leaves the box, it should revert to its original state. However, I am encountering some bugs in my current implementation on jsfiddle.

Answer №1

Check out this code snippet on JSFiddle

$('.box').hover(function(){
$(this).siblings().addClass('inactive');
}, function(){
$(this).siblings().removeClass('inactive');
});

I attempted to achieve the same effect using only CSS, but unfortunately, there is no equivalent of a "previous sibling selector" in CSS. The behavior may seem a bit jumpy due to the immediate change in z-index on hover.

Answer №2

You can create a similar effect using just CSS

$(document).on('mouseenter', '.item', function(e){
    var me = $(this);
    $('.item').not(this).addClass('greyed');
});

$(document).on('mouseleave', '.item', function(e){
    $('.item').removeClass('greyed');
});
ul,li{
list-style:none;padding:0;margin:0;
}
ul{
    width:400px;
}
li, .item {
    width:100px;
    height:100px;   
}
li {
    float:left;
    position:relative;
}
.item {
    background-color: #eee;
    border:1px solid #ccc;
    position:absolute;
    z-index:1;
    -webkit-transition:all 0.3s ease-in-out;
}
.item:hover {
    width:110px;
    z-index:2;
}

.red{
  background: red;
}

.pink{
  background: pink;
}

.blue{
  background: blue;
}

.yellow{
  background: yellow;
}

.greyed{
    -webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */
    filter: grayscale(100%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<ul>
    <li>
        <div class="item red"></div>
    </li>
    <li>
        <div class="item blue"></div>
    </li>
    <li>
        <div class="item yellow"></div>
    </li>
    <li>
        <div class="item pink"></div>
    </li>
   
</ul>

Answer №3

These were the steps I took:

Initially, I identified that the background image specified in your css was invalid, so I substituted it with a regular background color (transparent black) which you can adjust as needed.

Next, I modified allBoxes.on('hover mousemove' to allBoxes.on('mouseover', and changed $('body').mousemove to allBoxes.on('mouseout'.

Subsequently, I eliminated the $busy flag tracking.

Lastly, I updated var currentBox = $('.active'); to

var currentBox = $(event.target);
.

var app = function () {
    var self = this;

    var allBoxes = $('.box');
    var shadow = $('#shadow');
    var busy = false;

    self.init = function () {
        self.events();
    };

    self.getBoxLeftPosition = function(id)
    {
        var left = 100;

        if (id == 'box2')
        {
            left = 300;
        } else if (id == 'box3')
        {
            left = 500;
        } else if (id == 'box4')
        {
            left = 700;
        }

        return left;
    };

    self.events = function () {

        allBoxes.on('mouseover', function(event) {
            event.stopPropagation();
            var currentBox = $(this);

            if (currentBox.hasClass('inactive') && !busy)
            {
                //busy = true;
                currentBox.removeClass('inactive').addClass('active').animate({
                    left: '-=30',
                    width: 260
                }, 400, function () {
                    //busy = false;
                });

                shadow.fadeIn(400);
            }
        });

        allBoxes.on('mouseout', function(event) {
            var currentBox = $(event.target);
            var leftValue = self.getBoxLeftPosition(currentBox.attr('id'));

            if (currentBox.length > 0)
            {
                currentBox.stop();
                currentBox.animate({
                    left: leftValue,
                    width: 200
                }, 300, 'swing', function () {
                    currentBox.removeClass('active').addClass('inactive');
                }, 300);

                shadow.fadeOut(300);
            }
        });

    };

    return self;
};

var main = new app();
main.init();
html, body {
  margin: 0;
}

.box {
  position: absolute;
  top: 120px;
  width: 200px;
  height: 420px;
}

.box div {
  text-align: center;
  color: white;
  position: absolute;
  top: 200px;
  left: 0;
  right: 0;
  font-size: 25px;
  font-weight: bold;
}

#box1 {
  left: 100px;
  background: pink;
}

#box2 {
  left: 300px;
  background: skyblue;
}

#box3 {
  left: 500px;
  background: orange;
}

#box4 {
  left: 700px;
  background: lightgreen;
}

#shadow {
  display: none;
  position: absolute;
  left: 0;
  top: 0;
  width: 1000px;
  height: 600px;
  
  /*background: url('https://lh6.googleusercontent.com/Vz0GTzpQVaxmlIvvGgg64CSxcYBbHzu7gMQERduJ4qjU5HAg8KfisFFQvIqvKL5Vn7LIy6HZ=w1920-h916');*/
  background-color: rgba(0,0,0,0.5);  /* transparent black */
  
  z-index: 10;
}

.inactive {
  z-index: 5;
}

.active {
  z-index: 20;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="box1" class="box inactive">
    <div id="copy1">Copy 1</div>
</div>

<div id="box2" class="box inactive">
    <div id="copy2">Copy 2</div>
</div>

<div id="box3" class="box inactive">
    <div id="copy3">Copy 3</div>
</div>

<div id="box4" class="box inactive">
    <div id="copy4">Copy 4</div>
</div>

<div id="shadow"></div>

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

The html.dropdown feature is not maintaining the selected value chosen

After successfully filling out my form and submitting data to the database, I encountered a problem with the drop downs on the form not showing the selected value if the model fails validation. Although the HTML clearly shows that the value of the dropdow ...

Implementing Alloy-Script/Javascript in dynamically loaded JSP files

I have been loading various JSPs dynamically using an Ajax call, but after the JSP is loaded, none of the JavaScript inside seems to be working. I suspect this is because the script has not been parsed yet. To address this issue, I came across the "aui-pa ...

To modify the specified variables in data, I must deconstruct the object

Hello everyone, this is my debut post. I am seeking assistance with destructuring in order to update a variable that is defined within the "data" section. Below are the code snippets I have been working on using Vue. data: () => ({ id: '' ...

Unusual spacing issue observed between <div> elements on Internet Explorer, but not on Firefox or Opera

I am facing a common question that many others may have asked before, but I haven't been able to find a solution to my specific issue. When viewing my website on FF, Opera, and IE on Windows 7, everything displays correctly. However, when using IE7 o ...

Photographs housed within a pop-up window

My popover is causing me some trouble: I've got a popover that displays PHP-generated content without a fixed height, and I want to add an image inside it. The tooltip appears over my element like this: The problem is that if the image isn't pr ...

Tips for Aligning Images of Various Sizes in the Center of a div

My images are displayed in a horizontal line, but some have different sizes. I want to center all the images within their container div for a better look. Is there a way to do this automatically with CSS so that the images remain centered regardless of siz ...

Display the ViewModel in the view once the ajax call has been made

When I make an AJAX call to invoke an action, pass my ViewModel to it, and then attempt to open a new view with a different ViewModel, the redirectToAction and return view methods are not functioning as expected. Other solutions I have come across only inv ...

Passing an anonymous function as a parameter to a function in ng-init is a common practice in AngularJS v1.4.8

Is it possible to save a call to an anonymous function using ng-init? For example: <div class="container-fluid" ng-app="AVF" ng-controller="ConfigController" ng-init="RegisterInitFunction(function() { $scope.GetData(); })" > In my controller: ...

Guidance on invoking the navigate function from a component displayed at the highest level of rendering

Within the react-navigation documentation, it is explained that you can initiate navigation from the top-level component using the following method: import { NavigationActions } from 'react-navigation'; const AppNavigator = StackNavigator(SomeA ...

Using JavaScript to convert date and time into ISO format

Similar Question: How do I output an ISO-8601 formatted string in Javascript? I've been attempting to change a date and time input into an ISO format but keep encountering the error .toISOString is undefined. It seems like I must be overlooking s ...

Activate onbeforeunload when the form is not submitted

Currently, I have a form that is submitted using PHP with three different submit actions: Save and Continue Save and Exit Exit without Saving The goal is to trigger an "OnBeforeUnload" alert if the user does not click on any of the form actions. This al ...

Varying heights based on the screen size

Currently, I am in the process of designing my website and incorporating some wave elements to enhance the background. However, I've encountered some issues when resizing the screen. Specifically, the waves seem to shift with a space between them as t ...

Is there a way to combine several WAV audio blobs into one cohesive file?

Issue I'm Facing: I am attempting to combine multiple blob audio files into a single blob and then download it on the page. My Attempts So Far: I have tried to merge the Audio blobs using the following methods: Method - 1: const url = window.URL.c ...

Can the keys of an object be retrieved in a specific order?

Is it possible to retrieve keys from a JSON object in the exact same order they were originally received? The use of Object.keys(company).length currently seems to be functioning, but I am seeking reassurance that this method will consistently deliver acc ...

Showcasing articles in an XML feed according to specific keywords found in the headline

I'm currently working on designing a website for a client and I want to minimize my involvement in its maintenance. I am considering using RSS feeds to automate the process by having content posted on Blogger and then feeding it to the site. However, ...

An error occurred while trying to serialize the `.res` response received from the `getServerSideProps` function in

I encountered the following issue while utilizing the getServerSideProps function to fetch data from Binance API. import binance from "../config/binance-config"; export async function getServerSideProps() { const res = await binance.balance(( ...

Cross-site JSON communication without JSONP

I have a device connected to my local network that I can access using its IP address in order to retrieve JSON data. While developing a web-based application, I encountered an issue where the app couldn't access the local JSON data due to cross-domai ...

Send various pieces of information using Jquery/Ajax

I have encountered a challenge with my script - it currently only sends one value to the requested URL, but I now need it to handle two values. Unfortunately, I haven't been able to figure out how to do this. Each checkbox on the page is paired with ...

Automated logout feature will be enabled if no user interaction is detected, prompting a notification dialog box

Here is my working script that I found on this site. After a period of idle time, an alert message will pop up and direct the user to a specific page. However, instead of just the alert message, I would like to implement a dialog box where the user can ch ...

How can we show a varying number of textfields based on user selection using hooks and updating values dynamically through onChange events?

Currently, I am in the process of setting up a form that includes a Material UI select field ranging from 1 to 50. My challenge is how to dynamically display multiple textfields for "First Name and Last Name" using Hooks each time the user selects a number ...