I am attempting to delay the swapping of text in a div. It should operate like a slider/carousel for text.
I must have the code wrong, as the final text replacement never happens.
Also, how would I animate introducing the replacement text (window blinds, for eg.)?
<html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" /> <script type="text/javascript"> $(document).ready(function() { $("#showDiv").click(function() { $('#theDiv').show(1000, function() { setTimeout(function() { $('#theDiv').html('Here is some replacement text', function() { setTimeout(function() { $('#theDiv').html('More replacement text goes here'); }, 2500); }); }, 2500); }); }); //click function ends }); //END $(document).ready() </script> </head> <body> Below me is a DIV called "theDiv".<br><br> <div id="theDiv" style="background-color:yellow;display:none;width:30%;margin:0 auto;"> This text is inside the Div called "theDiv". </div><br> <br> <input type="button" id="showDiv" value="Show DIV"> </body> </html>
The Basic syntax for setTimeout function is, setTimeout(function() { // Do something after 2 seconds }, 2000); The setTimeout function takes the times in miliseconds. And the block can contain either your jQuery code, or you can also make a call to any function.
jQuery delay() Method The delay() method sets a timer to delay the execution of the next item in the queue.
Purpose of setTimeout function The setTimeout() function of JavaScript is used to delay certain action or execution of the code placed directly inside that function or at another JS function. The delay or time is specified in milliseconds in setTimeout function.
No, setTimeout does not pause execution of other code.
.html()
only takes a string OR a function as an argument, not both. Try this:
$("#showDiv").click(function () { $('#theDiv').show(1000, function () { setTimeout(function () { $('#theDiv').html(function () { setTimeout(function () { $('#theDiv').html('Here is some replacement text'); }, 0); setTimeout(function () { $('#theDiv').html('More replacement text goes here'); }, 2500); }); }, 2500); }); }); //click function ends
jsFiddle example
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