Is it possible to combine together addClass and fadeIn in JS? I'm trying to develop a script where on text hover (the title), the div container change background fading in/out (the whole section).
$(document).ready(function () {
$('#1st').hover(function () {
$('#BG').addClass('first');
$('#BG').removeClass('second');
});
$('#2nd').hover(function () {
$('#BG').addClass('second');
$('#BG').removeClass('first');
});
});
I tried to add the fading effect but without success.
$(document).ready(function () {
$('#1st').hover(function () {
$('#BG').stop(true, true).addClass('first', 400);
$('#BG').stop(true, true).removeClass('second', 400);
});
$('#2nd').hover(function () {
$('#BG').stop(true, true).addClass('second', 400);
$('#BG').stop(true, true).removeClass('first', 400);
});
});
Is there a way to make them working together?
Thanks in advance for any kind of suggestions :-)
CodePudding user response:
Something like below, you can add/remove class before/after fadeIn/fadeout.
$(document).ready(function(){
$("#1st").hover(function(){
$("#BG").fadeOut(400,function(){
alert("fadeOut() done!");
});
});
$("#2nd").hover(function(){
$("#BG").fadeIn(400,function(){
alert("fadeIn() done!");
});
});
});
CodePudding user response:
Thanks for your answer @何聊生
I made a CodePen to show better what I'm trying to do. When you hover a title, the background appear but without any sort of transition.
Is it possible to add the fadeIn to the current item you are hovering and fadeOut the other one?
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{
width: 100%;
height: 100%;
min-height: 500px;
text-align: center; }
.title{
margin: 50px auto;
font-size: 5em;
font-weight: 400; }
.first {
width: 100%;
height: 100%;
background: url(https://cdn.pixabay.com/photo/2022/11/03/15/24/coffee-7567749_960_720.jpg);
background-repeat: no-repeat;
background-attachment: relative;
-webkit-background-size: cover;
-moz-background-size: cover;
-ms-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-position: center center;
position: relative; }
.second {
width: 100%;
height: 100%;
background-image: url(https://cdn.pixabay.com/photo/2022/10/25/13/28/hanoi-7545860_960_720.jpg);
background-repeat: no-repeat;
background-attachment: relative;
-webkit-background-size: cover;
-moz-background-size: cover;
-ms-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-position: center center;
position: relative; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<section id="BG">
<div id="1st" >TITLE</div>
<div id="2nd" >TITLE 2</div>
</section>