How do I switch the background-image on li hover and revert it back when I move off the li element?

Looking to update the background image of a div upon hovering over a li element? Check out this example here. So far, I've got that part working fine. But now I want the background picture to revert back to its original CSS when I move away from the li element. Currently, the div retains the last li's image even after hover.

Here's My HTML:

<section class="content">
  <div class="projects">
        <ul>
            <li data-background="https://static.pexels.com/photos/7045/pexels-photo.jpeg"><a href="#">CASE I</a></li>
            <li data-background="https://static.pexels.com/photos/132037/pexels-photo-132037.jpeg"><a href="#">CASE II</a></li>
            <li data-background="https://iso.500px.com/wp-content/uploads/2016/11/stock-photo-159533631-1500x1000.jpg"><a href="#">CASE III</a></li>
            <li data-background="https://static.pexels.com/photos/7045/pexels-photo.jpeg"><a href="#">CASE IV</a></li>
        </ul>
    </div>

<div id="background">
    <h1 style="color:#fff;">RICHIE / WEB DESIGN / UI / UX / BLABLABLA</h1>
</div>
</section>

My CSS:

    .projects ul{
       list-style-type:none;
    }
    .projects a{
        display:inline-block;
        padding:10px;
        text-decoration: none;
        color:#434343;
        font-size: 20px;
        text-transform: uppercase;
        font-family: 'Sorts Mill Goudy', serif;
        line-height: 20px;
        text-indent: -50px;
    }

    .projects a:hover{

    }


    .projects ul:hover li {
        opacity: .5;
        transition: all 0.3s ease-in-out 0s;
        -moz-transition: all 0.3s ease-in-out 0s;
        -webkit-transition: all 0.3s ease-in-out 0s;
        -o-transition: all 0.3s ease-in-out 0s;
    }

    .projects ul li:hover {
        opacity: 1;
         transition: all 0.3s ease-in-out 0s;
        -moz-transition: all 0.3s ease-in-out 0s;
        -webkit-transition: all 0.3s ease-in-out 0s;
        -o-transition: all 0.3s ease-in-out 0s;
    }

#background {
background: url("https://www.aviary.com/img/photo-landscape.jpg");
    width: 50%;
    height: 100%;
    position: fixed;
    background-size: cover;
    padding:50px;
    background-position: center 30%;
}

My JS:

var links = $(".projects li");

links.on("mouseover",function(){
    var url = $(this).attr("data-background");
    $("#background").css("backgroundImage","url("+url+")");
});

I believe it might just require a minor adjustment in the JQuery code, but I'm struggling to pinpoint exactly what needs to be added or altered.

Thank you for your assistance! If my explanation is unclear, please let me know so I can provide further clarification.

Answer №1

To incorporate the mouseout function into your JavaScript, simply reference the URL of the background-image from your original CSS rule:

links.on("mouseout",function(){
    var url = $(this).attr("data-background");
    $("#background").css("backgroundImage","url('https://www.aviary.com/img/photo-landscape.jpg')");
});

https://jsfiddle.net/t0n0u5yv/

Answer №2

Here is the solution for you! Implement .mouseleave()

var links = $(".projects li"),
    sDefaultUrl = 'https://www.aviary.com/img/photo-landscape.jpg';

links
.mouseover(function(){
    var sUrl = $(this).attr("data-background");
    $("#background").css("backgroundImage","url(" + sUrl + ")");
})

.mouseleave("mouseover",function(){
    var url = $(this).attr("data-background");
    $("#background").css("backgroundImage","url(" + sDefaultUrl + ")");
});
.projects ul{
       list-style-type:none;
    }
    .projects a{
        display:inline-block;
        padding:10px;
        text-decoration: none;
        color:#434343;
        font-size: 20px;
        text-transform: uppercase;
        font-family: 'Sorts Mill Goudy', serif;
        line-height: 20px;
        text-indent: -50px;
    }

    .projects a:hover{

    }


    .projects ul:hover li {
        opacity: .5;
        transition: all 0.3s ease-in-out 0s;
        -moz-transition: all 0.3s ease-in-out 0s;
        -webkit-transition: all 0.3s ease-in-out 0s;
        -o-transition: all 0.3s ease-in-out 0s;
    }

    .projects ul li:hover {
        opacity: 1;
         transition: all 0.3s ease-in-out 0s;
        -moz-transition: all 0.3s ease-in-out 0s;
        -webkit-transition: all 0.3s ease-in-out 0s;
        -o-transition: all 0.3s ease-in-out 0s;
    }

#background {
background: url("https://www.aviary.com/img/photo-landscape.jpg"); 
    width: 50%;
    height: 100%;
    position: fixed;
    background-size: cover;
    padding:50px;
    background-position: center 30%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<section class="content">  
  <div class="projects">
        <ul>
            <li data-background="https://static.pexels.com/photos/7045/pexels-photo.jpeg"><a href="#">CASE I</a></li>
            <li data-background="https://static.pexels.com/photos/132037/pexels-photo-132037.jpeg"><a href="#">CASE II</a></li>
            <li data-background="https://iso.500px.com/wp-content/uploads/2016/11/stock-photo-159533631-1500x1000.jpg"><a href="#">CASE III</a></li>
            <li data-background="https://static.pexels.com/photos/7045/pexels-photo.jpeg"><a href="#">CASE IV</a></li>          
        </ul>
    </div> 

<div id="background">
    <h1 style="color:#fff;">RICHIE / WEB DESIGN / UI / UX / BLABLABLA</h1>
</div>
</section>

Answer №3

To add a dynamic mouseleave effect to your website, consider utilizing jQuery's mouseleave event.

Visit this link for more information on jQuery mouseleave event.

links.mouseleave(function(){
    var url = $(this).attr("data-background");
    $("#background").css("backgroundImage","url("+[your-original-url]+")");
});

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

Exploring the magic of the (!!!) operator in JavaScript!

The !! operator proves to be quite helpful when converting non-boolean data types into Boolean values, mainly for "True" conditions. However, when it comes to false conditions, is using !!! necessary? ...

Learn how to subscribe to Azure Event Grid using Angular without the need for a backend service layer

I am currently working on an Angular project and I am looking to set up Azure Event Grid subscription directly from the client-side without the need for a backend service. After exploring different options, I have not yet found a straightforward solution. ...

Conceal a div containing a specific class during the page's loading process, then reveal it once the

Is there a way to hide a specific div class while a page is loading? Here is the structure I am working with: <div id ="container"> <div class="project-item tv"></div> <div class="project-item radio"></div> <div class="pro ...

Finding documents in MongoDB where the size of an array exceeds 1

Looking to retrieve documents with an array size greater than 1 in my MongoDB collection Here is a snapshot of my collection: { "_id" : ObjectId("5eaaeedd00101108e1123452"), "type" : ["admin","teacher" ...

Unable to adjust the top padding of the navbar to 0 pixels

Having recently started learning HTML and CSS, I am encountering an issue with the padding on my navbar. I am unable to get it to align with the top of the site as there is a persistent space between the navbar and the top. Below is my HTML code: <!do ...

Why is my PanResponder failing to detect changes in the updated state?

This is the code snippet I'm currently working on: const processPinch = (x1: number, y1: number, x2: number, y2: number) => { function calcDistance(x1: number, y1: number, x2: number, y2: number) { const dx = x1 - x2; const dy = y1 ...

Is it possible to integrate a JavaScript library into the Vue prototype?

I've recently integrated ProgressBar.js library into my app, which is built using vue and laravel with laravel mix. After installing ProgressBar.js via npm install, I am unsure how to incorporate it into my .vue files. I'm considering adding it t ...

How can I show a view page in a specific div element using CodeIgniter?

Here is how I'm implementing the dashboard view in my controller. My goal is to have a specific page, like the index page, displayed within a div element rather than opening in a new tab. public function index() { $this->load->view('in ...

Obtaining the attribute value of a disabled element in an Angular JS application

Currently, I am struggling to retrieve the attribute value of a disabled element during runtime and then assert its value. The code I'm using is not providing the desired result: softAssert.assertFalse(shrSub.nextButton().waitForPresent().getAttribu ...

Tips for positioning an element in the center of a page using Bootstrap both horizontally and vertically

[Pardon my English] I recently managed to center my "logo" both horizontally and vertically. However, I am looking to have my logo shrink a bit when resizing the browser. Any suggestions on how to achieve this using bootstrap? Index.html <section> ...

Scroll vertically within a Xamarin Android ListView

I have been attempting to implement a vertical scroll for a list view, but I am facing an issue where all the list view items are displayed even if they exceed the phone's screen size. This is the code snippet I have been using: <LinearLayout xm ...

Querying cookies using Jquery/Ajax

Is there a way to trigger an ajax call when a page detects the presence of a cookie? I'm having trouble getting the ajax call to work in the code below. Any assistance would be greatly appreciated. EDIT: I have updated the code and it is now function ...

Experiencing Setbacks while Implementing AJAX in a PHP Object Orient

I'm currently attempting to create an object-oriented programming (OOP) login system using Ajax. However, I am encountering issues with starting the session or being redirected to the "Directivo.php" page. When I run the code, there is no output displ ...

Learn the process of dynamically expanding a specific Bootstrap menu item using jQuery!

To create a left vertical (sidebar) navigation menu, I will be referencing the "Example" located at https://getbootstrap.com/docs/5.0/components/accordion/. Assuming there are three HTML buttons: <button onclick="myFunction1()">Button 1< ...

Retrieve the attribute values of an element in Angular after utilizing a template

As a newcomer to Angular, I am exploring the use of custom directives for the first time. Currently, I have a table where each cell contains a data attribute such as "data-dept="service". Before applying a directive to overwrite this value, I would like to ...

Determine the location based on the preceding parameter of $routeChangeError using AngularJS

I am currently monitoring events of the type $routeChangeError within a run block in my application. $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) { if (!!previous) { console.log(previous); $locati ...

Retrieve duplicate data from the database by utilizing jQuery AJAX on mouse movement

I retrieved data from a database and it is stored in display.php. However, when using mousemove to view the data, it keeps repeating every time I hover over it. Here is the code for the mouse move function: $(line.node).mousemove(get_over_handler(country ...

Showing a series of JavaScript countdowns consecutively

I am working on a project where I want to display a second countdown after the first one finishes using meteor. The initial timer code looks like this: sec = 5 @timer = setInterval((-> $('#timer').text sec-- if sec == -1 $('#time ...

Tips for saving data in a database using Ajax with ExtJS?

In my current project, I have a set of items displayed in a row-wise order in the view using JavaScript. My goal is to implement an auto-save feature that will save the details of the clicked rows into a database using AJAX within ExtJS. ...

Ways in which an ajax response containing a string can be utilized to populate an HTML table by leveraging PHP, MySQL, and

Is there a way to populate an HTML table with data retrieved from an AJAX call? I have a string returned from the AJAX request that looks like this: 1-1.00-2013-2014,2-2.00-2013-2014,3-3.00-2013-2014,4-4.00-2013-2014,6-5.00-2013-2014,8-6.00-2013-2014,10-7 ...