I have the following code -
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function toggleText(){
if ($("#txt-1").css("display") != "none") {
$("#txt-1").css("display", "none");
$("#txt-2").css("display", "block");
$("#txt-3").css("display", "none");
} else if ($("#txt-2").css("display") != "none") {
$("#txt-1").css("display", "none");
$("#txt-2").css("display", "none");
$("#txt-3").css("display", "block");
} else {
$("#txt-1").css("display", "block");
$("#txt-2").css("display", "none");
$("#txt-3").css("display", "none");
}
};
</script>
</head>
<body>
<button onclick="toggleText()">Toggle</button>
<p id="txt-1">Hello</p>
<p id="txt-2" style="display: none;">How are you?</p>
<p id="txt-3" style="display: none;">See you soon!</p>
</body>
</html>
It toggles the text on button click
The thing that I am looking for is, to make a smooth transition between the texts (maybe fade in-out). I am not sure whether to write a CSS
or jQuery
.
What I tried is to write a CSS
class -
.smooth-fade {
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s;
}
and provide this class name smooth-fade
to all the h1
tags. It does not work, what is the best workaround to do this task ?
You can use jquery for this:
$( "#txt-1" ).fadeOut( "slow", function() {
$("#txt-2").fadeIn();
});
First fade out the elements you want, then use the callback function to fade the others in.
function toggleText(){
$( "#txt-1" ).fadeOut( "slow", function() {
$("#txt-2").fadeIn();
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="toggleText()">Toggle</button>
<p id="txt-1">Hello</p>
<p id="txt-2" style="display: none;">How are you?</p>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments