There are already some answers on this site but couldn't figure out what I need.
Using the answer accepted as good given here: How can I change text after time using jQuery?
But, instead of having an alert, I'd like to make it reload to its first message (adding full codes for clarity:
function nextMsg() {
if (messages.length == 0) {
// once there is no more message, I don't know how to start the script over (loop it)
} else {
$('#message').html(messages.pop()).fadeIn(500).delay(1000).fadeOut(500, nextMsg);
}
};
var messages = [
"Hello!",
"This is a website!",
"You are now going to be redirected.",
"Are you ready?",
"You're now being redirected..."
].reverse();
$('#message').hide();
nextMsg();
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
</html>
On another answer I had also find something similar, but I couldn't add fade in and fade out:
var example = ['<a href="#"> link1</a>', '<a href="#"> link2</a>'];
textSequence(0);
function textSequence(i) {
if (example.length > i) {
setTimeout(function() {
document.getElementById("sequence").innerHTML = example[i];
textSequence(++i);
}, 5000); // milliseconds
} else if (example.length == i) { // Loop
textSequence(0);
}
}
<div id="sequence"></div>
This may seem like a simple answer, but while I understand html and css to an extent, jscript is still out of my reach, so an answer with some clarity onto it would be great.
Thanks to anyone that will answer.
Using pop
in the first example is actively removing elements from your messages
array - so you can't "start the script over" because you have basically destroyed your data.
Think of pop
as taking an items out of a bag one at a time and throwing them away - obviously when there are no items left in the bag - you can't then start again trying to get items out of the bag - because there is nothing left in the bag.
function nextMsg(index) {
if (messages.length === index) {
nextMsg(0);
} else {
$('#message').html(messages[index])
.fadeIn(500)
.delay(1000)
.fadeOut(500, () => nextMsg(index + 1));
}
};
var messages = [
'<a href="#"> link1</a>',
'<a href="#"> link2</a>',
'<a href="#"> link3</a>',
'<a href="#"> link4</a>'
];
$('#message').hide();
nextMsg(0);
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
As you can see there is no need to copy
or duplicate the data - nor is there any need to reverse
the messages.
Simply use the message index to keep track of which message to display and loop the index.
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