I am new to jQuery and I am trying a simple program. In this program what I am trying to achieve is that when I will click the div text then first line will fadeout then it will change background colour and then it will fade in so overall it will give effect of changing colour slowly, but what happening here is when I click the text the line changes colour suddenly then it fades out and then it fades in. So I was wondering if there is a way to make colour changing code execute after execution of fadeout.
my program:
$(document).ready(function(){
$("#firstDiv").click(function(){
// $(this).fadeOut(1000);
$(this).fadeOut(1000);
$(this).css("background-color", "aqua");
$(this).fadeIn(1000);
});
});
</script>
</head>
<body>
<div id="firstDiv" style="background-color: yellowgreen">
Click Me
</div>
</body>
You should use a callback parameter: function Typer(callback) { var srcText = 'EXAMPLE '; var i = 0; var result = srcText[i]; var interval = setInterval(function() { if(i == srcText. length - 1) { clearInterval(interval); callback(); return; } i++; result += srcText[i].
Answer: Use the JavaScript setInterval() method You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.
You have to use <br> to have line breaks. You can replace line breaks to <br> just for display.
By default, jQuery uses "$" as a shortcut for "jQuery" So, using $("#id" ) or jQuery("#id") is the same. Follow this answer to receive notifications.
You have to put the color changing in a callback passed to fadeOut
:
$(this).fadeOut(1000, function() {
$(this).css("background-color", "aqua");
}).fadeIn(1000);
Everything you put in the callback is executed after fadeOut
finished. fadeIn
is not executed immediately because effect methods are queued automatically.
But: If you are doing something computational expensive (i.e. it takes time) in the callback and you want to call fadeIn
only after this has finished, you have to put fadeIn
in the callback too:
$(this).fadeOut(1000, function() {
$(this)
.css("background-color", "aqua")
.fadeIn(1000);
});
Otherwise fadeIn
will be called before the callback finished.
Also worth reading in this context: Can somebody explain jQuery queue?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With