I’m trying to make a text fade in and fade out, alternately, as you click a button, using jQuery. I came up with this code:
JavaScript
x
8
1
$("button").click(function() {
2
$('#p1').fadeIn();
3
4
$("button").click(function() {
5
$('#p1').fadeOut();
6
$('button').off("click");
7
});
8
});
JavaScript
1
4
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
3
<button>Button</button>
4
<p id='p1'> Paragraph </p>
That works only once (fades in first click, fades out second) and the button stops working forever.
If I comment out line 5, the button works once and everytime I press it again, the text fades in and out at the same time, which is not what I want.
What am I doing wrong?
Advertisement
Answer
There is a method fadeToggle()
which toggles between fadeIn and fadeOut.
JavaScript
1
3
1
$("button").click(function() {
2
$('#p1').fadeToggle();
3
});
JavaScript
1
3
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
2
<button>Button</button>
3
<p id="p1">Paragraph</p>