is it possible to combine together addClass and fadeIn with JS?
I'm not really practice with JS but I'm trying to develop a script where on text hover, the div container change background fading in/out.
I made a CodePen to show better what I'm trying to achieve. When you hover a title, the background appear but without any sort of transition.
https://codepen.io/Freddan3/pen/NWzpKRz
$(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" >TITLE</div>
<div id="2nd" >TITLE 2</div>
</section>
Is it possible to add the fadeIn to the current item you are hovering and fadeOut the other one?
Thanks in advance for any kind of suggestions :-)
CodePudding user response:
You could use a second div
arround your #BG
and give both different background-image
s:
<div id="container">
<div id="BG">
<h2 id="1st">First</h2>
<h2 id="2nd">Second</h2>
</div>
</div>
#container {
background-image: url(https://cdn.pixabay.com/photo/2022/11/03/15/24/coffee-7567749_960_720.jpg);
}
#BG {
background-image: url(https://cdn.pixabay.com/photo/2022/10/25/13/28/hanoi-7545860_960_720.jpg);
}
Then you would animate the opacity
of #BG
on hover:
$('#1st').hover(function () {
$('#BG').animate({opacity: 0}, 1000);
});
$('#2nd').hover(function () {
$('#BG').animate({opacity: 1}, 1000);
});
To prevent the content (#1st
and #2nd
) to fade away too, you could wrap it in an extra 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;
}
Working example: (simplified for demonstration)
$('#1st').hover(function () {
$('#BG').animate({opacity: 0}, 1000);
});
$('#2nd').hover(function () {
$('#BG').animate({opacity: 1}, 1000);
});
#container {
background-image: url(https://cdn.pixabay.com/photo/2022/11/03/15/24/coffee-7567749_960_720.jpg);
}
#BG {
height: 100px;
background-image: url(https://cdn.pixabay.com/photo/2022/10/25/13/28/hanoi-7545860_960_720.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>