Reputation: 3231
I'm trying to make a fadeToggle
effect on jQuery,
the toggle effect works fine only in the second click on the <h1>
tag.
in the first click it showing up and hide right after.
noticed that if I remove the text("how are you")
method and put the inside the paragraph tag, it works perfectrly.
wondering why it doesn't work the first way. This is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('h1').click(function(){
$('p').text("how are you").fadeToggle(500);
});
});
</script>
</head>
<body>
<h1>Hello jquery</h1>
<p></p>
</body>
</html>
Upvotes: 1
Views: 53
Reputation: 41893
fadeToggle
works the same way as e.g. toggle
(applies opposed attribute). And since the default state for the p
element at the begininng is display: inline
(is visible), then the next default action will be hiding it. That's why you have to define it initially as hidden.
$(document).ready(function() {
$('h1').click(function() {
$('.x').text("how are you").fadeToggle(500);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Hello jquery</h1>
<p class='x' hidden></p>
Upvotes: 3
Reputation: 871
It works correctly actually - the paragraph element is shown and by clicking on the heading, the function inserts text in it and then toggles fade. As the element is shown, by default (since there are no rules attached to it that would otherwise hide it), the fadeToggle will transition from shown to hidden state.
As stated in the comment above, to make fadeToggle begin by fading an element in, you should first hide the element (either via CSS or via JS, depending on your needs).
Upvotes: 1