What is the best way to create an animation for a dynamic menu background image

While hovering over a list item, I want to create an animation where the background image appears to zoom out.

$(function () {
    var image = $('.menu').find('img').attr('src');
    $('.menu ul li').mouseover(function () {
        var currentImage = $(this).attr('data-img');
        $(this).parent().parent().parent().parent().find('img').attr('src', currentImage); })});
::-webkit-scrollbar{display: none; visibility: hidden;}
body{margin: 0; background: burlywood; }
.menu {  position: relative;  text-align: center;  margin: auto;  height: 100%;  padding-top: 2%;  padding-bottom: 10%; z-index: 99;}
.menu li{ display: block; font-size: 1.5rem; font-family: "Raleway SemiBold", Serif, sans-serif; padding-bottom: 20px;}
.menu li+li{margin-top: 30px;}
.menu a{ font-size: 3.5rem;}
.navigationGif{ position: fixed; top: 0; bottom: 0; left: 0; right: 0; animation: menuBG 0.7s ease-in;}
.homeGif{ position: fixed;}
.menu img{ width: 100%; }
@keyframes menuBG { from{ opacity: 0; transform: scale(1.05); }}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu">
        <div class="navigationGif">
            <div class=""> <img src="https://images.unsplash.com/photo-1532109513327-3b32b2a9bd57?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80" alt="" class="src"> </div> </div>
        <div class="menu"> <div class="data"><ul>
                 <li>Navigation</li>
<li data-img="https://images.unsplash.com/photo-1532109513327-3b32b2a9bd57?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80" class="navLink home active"><a href="" class="navItem"><span>H</span><span>o</span><span>m</span><span>e</span></a></li>
<li data-img="https://images.unsplash.com/photo-1589986118236-64c32953ab27?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80" class="navLink works"><a href="" class="navItem">Works</a></li>
<li data-img="https://images.unsplash.com/photo-1589892889837-e0236f8dd22e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=753&q=80" class="navLink about"><a href="" class="navItem">About</a></li>
<li data-img="https://images.unsplash.com/photo-1558567083-b8cb6bb5f7d9?ixlib=rb-1.2.1&auto=format&fit=crop&w=763&q=80" class="navLink contact"><a href="" class="navItem">Contact</a></li></ul> </div></div></div>

Answer №1

Consider resetting the animation and minimizing the use of parent() calls by targeting the closest element or utilizing more descriptive class names. To achieve the desired functionality, a slight modification can be made by adding a class to the background image that triggers the animation. This way, each time you hover over another menu item (LI element), the class name will toggle, causing the animation to restart.

$(function () {
  var image = $('.menu').find('img').attr('src');
  var lastImage
  $('.menu ul li.navLink').mouseover(function () {
    var currentImage = $(this).attr('data-img');
    $('.navigationGif img').attr('src', currentImage);
    if(lastImage !== currentImage) {
      $('.navigationGif').removeClass('animation')
      setTimeout(() => {
        $('.navigationGif').addClass('animation')
      }, 10);
      lastImage = currentImage
    }
  })
});
::-webkit-scrollbar {
  display: none;
  visibility: hidden;
}

body {
  margin: 0;
  background: burlywood;
}

.menu {
  position: relative;
  text-align: center;
  margin: auto;
  height: 100%;
  padding-top: 2%;
  padding-bottom: 10%;
  z-index: 99;
}

.menu li {
  display: block;
  font-size: 1.5rem;
  font-family: "Raleway SemiBold", Serif, sans-serif;
  padding-bottom: 20px;
}

.menu li+li {
  margin-top: 30px;
}

.menu a {
  font-size: 3.5rem;
}

.navigationGif {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

.navigationGif.animation {
  animation: menuBG 0.7s ease-in;
}

.homeGif {
  position: fixed;
}

.menu img {
  width: 100%;
}

@keyframes menuBG {
  from {
    opacity: 0;
    transform: scale(1.05);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="menu">
  <div class="navigationGif animation">
    <div class=""> <img
        src="https://images.unsplash.com/photo-1532109513327-3b32b2a9bd57?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80"
        alt="" class="src"> </div>
  </div>
  <div class="menu">
    <div class="data">
      <ul>
        <li>Navigation</li>
        <li
          data-img="https://images.unsplash.com/photo-1532109513327-3b32b2a9bd57?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80"
          class="navLink home active"><a href=""

Using better class names can improve readability and maintainability in your code structure. 

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

Tips for implementing a conditional statement within an export default clause

I am completely new to web programming and I'm attempting to create a question-answer feature using Vue.js. export default { // Trying to implement an if statement (if character == "Past", then do these steps) "steps": [ { ...

Addressing Image Issues in CSS Grid

I'm struggling to position two images in different sections of a grid layout without overlapping them. I've attempted referencing the images by both their class and id, but they continue to occupy the same grid space. Referencing the images by ...

Initially Missing Child Props in Parent Component

I am currently working on an application that utilizes a nutrition API to fetch information such as calories and more. One of the key features I am developing is the ability for users to set their daily calorie target along with the percentage breakdown fo ...

Two selection options controlling filters. The first choice influences the data shown in the second filter

I've been struggling for hours to figure out how to build this functionality. My code seems to be getting close, but I'm having trouble passing my selection from the HTML back to the controller. Here's my Angular code: var Categories = Pa ...

Looking to set up an event listener for a customized checkbox in a Kendo UI Grid column with Vue Js?

Can someone help me figure out why my method checkboxToggle() is not working when I click on the checkbox? Here is the code snippet: ` Methods:{ toggleTemplate(){ let template = `<label class="switch" > <input type= ...

What are the steps to ensure that data retrieved from an API is accurately displayed in a table?

My current goal is to collect data from the crypto compare API and display it in a table format. Although I am able to generate the necessary elements and append them to the table body, I am facing an unusual issue. Each time I use a for loop to iterate th ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...

A guide on seamlessly transitioning from a mobile website to the corresponding native app

I am currently working on a mobile website project. This website is built using basic HTML and is accessed through a URL on a web browser, not as a native app or through PhoneGap. The client has requested links to their Facebook, Pinterest, YouTube, Twitt ...

Retrieve the scrollTop, scrollLeft properties, and other scroll-related data from an element using Selenium

When testing a Python/Django element that is scrolled using scrollTop, I am trying to retrieve the value of scrollTop. In JavaScript, I can access this value with: element.scrollTop I attempted to do this in Python using: element.get_attribute('sc ...

How can I apply a unique CSS class to specific rows within an h:dataTable?

I am looking to apply unique CSS classes to certain rows within my <h:dataTable>. Is it possible to manipulate and style the individual table rows in a customized manner? ...

A simple guide on integrating personalized color palettes into Material-UI Theme

One enhancement I'd like to make in my theme is the inclusion of a custom color called warn import React from 'react' import { MuiThemeProvider } from '@material-ui/core/styles' import createMuiTheme from '@material-ui/core/s ...

Blackberry Browser's Window.Opener Feature

Does anyone else experience issues with the blackberry browser(5.0) and the javascript window.opener function? I couldn't find much help on Google regarding this problem. We have a pre-existing website that successfully populates parent window form f ...

Representation of a family tree in CSS showcasing multiple sub-parents (both many to one and one to many relationships)

I've come across various family tree presentations. I'm curious if it's possible to display a one-to-many and then many-to-one structure? Currently, the flow is linear stop after stop, but I'd like to incorporate multiple steps that con ...

Are there any methods to alter the current preFilters within jQuery?

Is there a way to access and manipulate the internal jQuery preFilters using the jQuery.ajaxPrefilter() function? In version 1.11.1, I noticed a private preFilters object declared on line 8568, but it doesn't seem like there is a built-in method to in ...

angular 6's distinctUntilChanged() function is not producing the desired results

I have a function that retrieves an observable like so: constructor(private _http: HttpClient) {} getUsers(location){ return this._http.get(`https://someurl?location=${location}`) .pipe( map((response: any) => response), ...

The reflight response received an unexpected HTTP status code of 500

Recently, I've been working on utilizing the Yelp Fusion API by making a simple ajax call. I started off by using the client_id and client_secret provided by Yelp to successfully obtain an access token through a 'POST' request in Postman, fo ...

Tips for changing the background color of a Qtextedit?

After experimenting with HTML, I discovered that using type bgcolor="#ffd814" will change the background color in textedit. But how can I achieve the same result using QAction and QColorDialog? This is the method I tried: void MainWindow::on_actionBackgr ...

Error encountered when attempting to integrate FontAwesome into the body of a Next.js Link

I'm currently using the react-fontawesome library in my project built with Next.js. However, I've encountered an issue when trying to include an icon inside the Link component. The error message is confusing and I can't seem to figure out wh ...

Trouble with formatting a HTML form

I have been working on dynamically creating HTML forms using a function called makeInput(). However, I am facing an issue where the text input boxes are appearing next to each other when I click the "Add Course" button, instead of one per line. Below is ...

Automatically add shimmer with CSS styling

Is it possible to make the shine effect work automatically (without needing hover) every 5 seconds? http://jsfiddle.net/AntonTrollback/nqQc7/ .icon:after { content: ""; position: absolute; top: -110%; left: -210%; width: 200%; height: 200%; ...