Revamping the Look: Refreshing Background of Div

I'm attempting to change the background image of the body element on a webpage when I hover over links with data-* attributes. It's working perfectly, but I can't seem to figure out how to create a smooth fade between the images when a link is hovered over. Here is my code:

$(document).ready(function() {
    $('.link').hover(
        function() {
            var bg = $(this).data('fond');
            
            // alert(bg);
            
            $('body').css("backgroundImage", 'url(' + bg + ')');
        },
        function () {
            $('body').css("backgroundImage", 'url(http://sport-nc.com/wp-content/uploads/2015/06/India_Surf_Tours_-_17__1_.jpg)');
        }
    );
});
body {
    margin:0;
    background-image: url("http://sport-nc.com/wp-content/uploads/2015/06/India_Surf_Tours_-_17__1_.jpg");
    background-repeat: no-repeat;
    background-size: cover;
    transition: all 1s;
}

header {
    width: 50%;
    margin: 50px auto;
}

h1 {
    text-align: center;
}

nav {
    position: absolute;
    width: 50%;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    text-align: center;
}

nav ul {
    padding: 50px;
    background-color: rgba(0, 0, 0, 0.95);
}

nav ul li {
    display: inline-block;
    padding: 0 20px;
}

nav ul li a {
    color: white;
    text-decoration: none;
}
<header>
      <h1>Hover a link, bro</h1>
    </header>
        <!-- Main -->
        <main> 
          <nav class="main-nav">
            <ul>
              <li data-fond ="img/belharra.jpg" class="link"><a href="#">Belharra</a></li>
              <li data-fond ="img/jaws.jpg" class="link"><a href="#">Jaws</a></li>
              <li data-fond ="img/mavericks.jpg" class="link"><a href="#">Mavericks</a></li>
              <li data-fond ="img/nazare.jpg" class="link"><a href="#">Nazare</a></li>
              <li data-fond ="img/teahupoo.jpg" class="link"><a href="#">Teahuppo</a></li>
            </ul>
          </nav>
        </main>

Bonus: Can anyone explain to me why I had to use a separate function when the mouse leaves a link in order to restore the body's original background image? I thought the .hover() method automatically toggles the targeted element...

The .hover() method binds handlers for both the mouseenter and mouseleave events. You can use it to simply apply behavior to an element while the mouse is within the element.

Thank you so much for your assistance!

Answer №1

In my opinion, achieving a smooth fade effect might be challenging in this situation.
However, there is an alternative approach that could work effectively. By organizing all your images within a div container in your html file, and setting their css opacity property to 0, you can manipulate the opacity values between the images seamlessly, resulting in a desirable smooth fade effect.

Answer №2

body {
    margin: 0;
    background-image: url("http://example.com/wp-content/uploads/2021/08/beautiful-beach.jpg");
    background-repeat: no-repeat;
    background-size: cover;
    transition: all 0.5s;
}

Please update the URL link

url("http://example.com/wp-content/uploads/2021/08/beautiful-beach.jpg");
. It needs to be corrected.

Answer №3

For a different approach in using jQuery, you can try this code snippet.

$('body').fadeOut(1000).css("your code").fadeIn(1000);

In order to provide you with an example, I have created the following HTML markup. Feel free to copy it and test it out.

<html>
<head>
<title>Welcome!</title>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<style type="text/css">
 .myimage{
    width:500px;
    height: 500px;
    overflow: hidden;
 }

 .myimage img{
    width: 100%;
    height: 100%;

 }


</style>


 <body>

  <div class="myimage">
    <img id="one" src="http://www.estero.co.nz/new/wp-content/uploads/2014/03/45901_new-zealand.jpg"/>
    <img id="two" src="http://www.timeforkids.com/files/styles/tfk_rect_large/public/2011-07/nz_ss5.jpg?itok=0m-TtEYy"/>
  </div>

<script type="text/javascript">
 $(document).ready(function(){
    $("#one").mouseenter(function(){
        $(this).fadeOut(1000);
    });
 });
</script>

 </body>
</html>

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

Creating dynamic scroll animations for sidebar navigation in a single-page website with anchor links

I need help creating a seamless transition between anchor points on a single page, while keeping a fixed navigation menu that highlights the active section. As a novice, I am unsure how to incorporate "( document.body ).animate" or any other necessary code ...

Use jQuery to calculate the width of the wrapper and evenly divide it among the div elements inside

Seeking assistance with a dynamic div wrapper containing multiple inner divs. The number of inner divs will vary, requiring a script to determine how many are present and adjust their widths to fit perfectly within the wrapper. <div id="wrapper"> &l ...

Is there a way to dynamically refresh the options in a select dropdown using jQuery?

I'm facing an issue with updating the options in a select element. Here is how my current select element looks: <select id="productId"> </select> Below is the jQuery code I am using: ... if (data.success) { var items = []; $.ea ...

Submitting a form using an anchor tag in Angular 8: A step-by-step guide

I have a question about how to submit form data using hidden input fields when a user clicks on an <a> tag. <form action="/submit/form/link"> <input type="hidden" [attr.value]="orderNumber.id" /> <input type="hidden" [attr.value]= ...

Click event for nested attributes in Angular 6 using JQuery is unresponsive

I'm having trouble getting a click listener to work in jQuery. It seems like nested attributes created in HTML are not being recognized by jQuery when trying to add the listener. I attempted to add a listener in the ngOnInit() method, but it doesn&ap ...

What is the best way to customize the text in the navigation bar at the top of the page

I'm having trouble with the Navigation Bar code in my header. The text is not staying within the header and I can't seem to fix it. Is there a CSS solution to keep the text contained within the header? <div class="header"> <img src= ...

Should we store $(this) in jQuery's cache, or leave it be?

When dealing with a selector such as $(this), does the act of creating and reusing a reference actually have a noticeable impact on performance? I find it more efficient to create references for jQuery selectors that are used repeatedly within the same sc ...

Implementing HTML page authentication with Identity ADFS URL through JavaScript

I have a basic HTML page that displays customer reports using a JavaScript function. The JavaScript makes an ajax call to retrieve the reports from a backend Spring REST API. In the Spring REST API, I have set up an endpoint "/api/saml" for authentication ...

What is the mechanism behind image pasting in Firefox's imgur integration?

Start by launching an image editing software and make a copy of any desired image. Avoid copying directly from a web browser as I will explain the reason later on. Navigate to "http://imgur.com" using Firefox. To paste the copied image, simply press Ctrl+V ...

The router is displaying the component directly on the current page rather than opening it on a separate page

The issue is that the router is rendering the page on the same page instead of generating a new one. When clicking on the Polls link, it only renders the page there but the URL changes in the browser. Polls.js import React from 'react'; import ...

What is the best way to reload DataTables using an ajax/error callback?

In my code, I am customizing the default settings of DataTables like this: $.extend(true, $.fn.dataTable.defaults, { lengthChange: false, deferRender: true, displayLength: 25, stateSave: false, serverSide: true, processing: true, ...

Have you checked the console.log messages?

As a newcomer to web development, I hope you can forgive me if my question sounds a bit naive. I'm curious to know whether it's feasible to capture a value from the browser console and use it as a variable in JavaScript. For instance, when I enco ...

Is there a way to automatically trigger an Anthem.NET button click event upon page load in ASP.NET?

My goal is to initiate the loading of an ASP.NET page followed by triggering a server-side event that will update some HTML on the client side. The event is associated with an Anthem.NET imagebutton control, so the most obvious approach would be to simply ...

Tips for displaying a message when clicking on the second level in fancytree.js

I'm looking to use fancytree.js to display an alert message only when clicking on nodes in the second level. For example: <ul> <li>1</li> <ul> <li>1.1</li> ...

Problem with Active State of DOM Element

My goal is to create an effect where clicking on a DOM element, specifically a list, will cause the target list to rotate and remain in that position. Describing it can be a bit challenging, so I have provided a visual example of what I'm working on ...

Prevent browser menus from opening by using JavaScript without triggering a new popup window

In seeking to safeguard the source code of my website, I am looking to prevent any unauthorized access. Therefore, I aim to deactivate all common methods of accessing the code such as Ctrl+U, Ctrl+Shift+I, F12, and browser menu options. ...

Tips for utilizing GSON and showcasing data in a JSP document

I am in the process of building a web application using JSP. One of the servlet classes I have created is as follows: package managesystem; import java.util.List; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; impor ...

Is it possible to return PHP parser errors as JSON data?

I am facing an issue with my HTML page that uses a JQuery Ajax call to communicate with a PHP page and expects a JSON response. If the PHP encounters a parser error, it sends back the error message but not in the expected JSON format. This leads to a "JSON ...

Converting API data in Angular using rxjs

Hey there, I received this response from an API: { "records":[ { "id":1, "motivazione":"", "autorizzazione":false, } ] } Can anyone help me transform it to loo ...

Combining a JavaScript NPM project with Spring Boot Integration

Recently, I built a frontend application in React.js using NPM and utilized IntelliJ IDEA as my IDE for development. Additionally, I have set up a backend system using Spring Boot, which was also developed in IntelliJ IDEA separately. My current goal is t ...