How can I combine addClass with fadeIn/fadeOut in JavaScript?

Can the addClass and fadeIn functions be combined in JS?

Although I'm not very experienced with JS, I'm working on a script where the div container changes background color by fading in and out on text hover.

I've created a CodePen to demonstrate what I'm trying to achieve. Currently, when you hover over a title, the background appears abruptly without any transition effect.

Check out the example here

$(document).ready(function () {
    $('#1st').hover(function () {
        $('#BG').addClass('first');
        $('#BG').removeClass('second');
    });
    $('#2nd').hover(function () {
        $('#BG').addClass('second');
        $('#BG').removeClass('first');
    });
});
section{
  min-height: 500px;
  text-align: center;
}

.title{
  margin: 50px auto;
  font-size: 5em;
  font-weight: 400;
}

.first {
    background: url(https://cdn.pixabay.com/photo/2022/11/03/15/24/coffee-7567749_960_720.jpg);
    background-size: cover;
}

.second {
    background-image: url(https://cdn.pixabay.com/photo/2022/10/25/13/28/hanoi-7545860_960_720.jpg);
    background-size: cover;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<section id="BG">
  <div id="1st" class="title">TITLE</div>
  <div id="2nd" class="title">TITLE 2</div>
</section>

Is it possible to fade in the current item being hovered over and fade out the other one using fadeIn? Any suggestions would be greatly appreciated :-) Thanks!

Answer №1

If you want to add a second layer around your #BG with different background images, you can do the following:

<div id="container">
  <div id="BG">
    <h2 id="1st">First</h2>
    <h2 id="2nd">Second</h2>
  </div>
</div>
#container {
  background-image: url(https://example.com/first-background.jpg);
}

#BG {
  background-image: url(https://example.com/second-background.jpg);
}

You can then animate the opacity of #BG on hover using jQuery:

$('#1st').hover(function () {
    $('#BG').animate({opacity: 0}, 1000);
});
$('#2nd').hover(function () {
    $('#BG').animate({opacity: 1}, 1000);
});

To avoid the content (#1st and #2nd) from fading away, wrap it in an additional div with position absolute:

<div id="container">
  <div id="BG"></div>
  
  <div id="content">
    <h2 id="1st">First</h2>
    <h2 id="2nd">Second</h2>
  </div>
</div>
#content {
  position: absolute;
  top: 0;
}

Check out the working example below:

$('#1st').hover(function () {
    $('#BG').animate({opacity: 0}, 1000);
});
$('#2nd').hover(function () {
    $('#BG').animate({opacity: 1}, 1000);
});
#container {
  background-image: url(https://example.com/first-background.jpg);
}

#BG {
  height: 100px;
  background-image: url(https://example.com/second-background.jpg);
}

#content {
  position: absolute;
  top: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="container">
  <div id="BG"></div>
  
  <div id="content">
    <h2 id="1st">First</h2>
    <h2 id="2nd">Second</h2>
  </div>
</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

Leveraging a standalone Vue project as a node package within another project

I'm facing a challenge in my projects due to architectural changes and am in need of some guidance to move forward. Here is the issue at hand. Situation Originally, I began with a single Vue application that included various components such as queryi ...

Guide to integrating search and clear icons into the bootstrap search bar

I am working on a project that requires me to add search and clear icons to a Bootstrap search box, similar to the design shown in the image below: Does anyone have suggestions on how to achieve this? ...

The database threw an error: "Duplicate key found in collection causing MongoError: E11000"

I'm currently in the process of updating an object within an array found in a document "state": [], "users": [{ "ready": false, "_id": { "$oid": "5fb810c63af8b3 ...

Ask the controller for information, then send it to the appropriate route before displaying it in

Within my HomeController, there is a method that requires specific arguments to function properly. public function mcQuery($ip, $port){ $Query = new MinecraftQuery(); try { $Query->Connect( $ip, $port ); return ...

The communication between Node.js Express and the front end is experiencing synchronization issues

I'm facing an issue where a property is mysteriously disappearing when I try to send an object from my nodejs server to the front end. server router.post('/cart/retrieve', (req, res) => { let cart = req.session.cart; let prodId ...

Endless repetition occurs when invoking a function within a v-for loop

I've encountered an issue while trying to populate an array using a method, leading to redundant data and the following warning message: You may have an infinite update loop in a component render function. Below is the code snippet in question: ...

Transforming a CSV file into JSON format using Gatsbyjs

I am currently exploring the possibilities of GatsbyJs and considering the utilization of the gatsby-transformer-csv plugin. You can find the documentation for this plugin here. I have got my hands on two CSV files exported from WordPress that I am eager ...

CSS implementation of a treeview with a dropdown submenu

I'm currently customizing an HTML tree view using CSS, and my goal is to have sublists smoothly slide down whenever a node is expanded. Take a look at my streamlined index.html : <!DOCTYPE html> <html> <head> <script data ...

Is it possible to retrieve a value within nested objects using only a single string as the reference?

Can a value inside a nested object be accessed with a single string? For example, consider the object below: skill: { skillDetails: { developerDetails: { developerName: "mr. developer" } } } Is there a way to retrieve ...

When the collapsed navbar is displayed, elements are pushed beyond the boundaries of their parent container (Bootstrap 5)

Introduction Utilizing Bootstrap 5 (included with webpack 5), I am implementing the grid system and collapse function to design the homepage of this website, featuring 2 sidebars that collapse into a top bar. On mobile devices, the navigation collapses a ...

Submitting a form and using Ajax to upload an image

Is there a way to submit an image file to php using ajax without assigning the file to a variable with onchange event? I've tried triggering the request on submit click, but keep getting the error message: "cannot read property 0 of undefined." <ht ...

Unable to add a logo to the header in react-material kit

I am in the process of trying to incorporate my logo into the top header section of the page, but I am facing some challenges with the code provided. import React from "react"; import classNames from "classnames"; import PropTypes from "prop-types" ...

Start up a server using Angular along with Node.js and Express framework

I am encountering an issue with configuring Express as a server in my Angular application. The app loads without any issues when accessing the HOME route, but when trying to access another route, I receive an error message: Cannot GET / This is how I hav ...

Can you navigate between slides with JQuery?

Looking to create a website similar to . The only obstacle I am encountering is understanding the code. I prefer using JQuery over MooTools. Is there anyone who can kindly assist me by providing a demo? I want to implement the functionality of switching b ...

Using JavaScript's setInterval function in conjunction with Math.random to obtain a random value

Just generated some random numbers. Wondering how to dynamically update the values of these numbers every 5 seconds with fluctuations less than +/- 5% compared to the current value. Need help using the setInterval function. Here is my code for Random Pric ...

Error: The function seems to be malfunctioning or missing

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $('div'); // <--- THIS DOESN'T WORK </script> An issue has been encountere ...

Setting up a autoRotate toggle feature in three.js using dat.gui - a step-by-step guide

I am currently working on a project involving 3 planets positioned next to each other. I have implemented a slider to independently move them along each axis and have set up an autoRotate feature. However, I am facing difficulty in integrating it as a togg ...

Bring in 2 Angular applications into a different JavaScript project

In my current setup, I have 2 distinct Angular projects. To build each project, I execute the following CLI command: ng build --prod --output-hashing=none Following this command, the build process generates the below files for each project: runtime.js ...

Is it problematic to incorporate jQuery into Angular applications?

Recently, while working on an Angular web application with Bootstrap accordion, I came across a helpful post that addressed a bug related to switching collapse/expand icons (you can view the post here). The post suggested a solution using basic jQuery. He ...

In bootstrap, two overlapping DIVs are displayed below each other in mobile mode

I have a setup with two divs. The initial div consists of a header bar containing navigation links and a logo. Directly below is the second div, which features a hero image accompanied by some text. These divs are nested within a header tag, with the fir ...