Rajesh Muntari
Rajesh Muntari

Reputation: 79

How to change text after time using jQuery?

I found this code on stackoverflow HERE , but it's not working for me...

I can see this only:

Hello world!
Here is a message: 

,but I don't see the messages that should be changing after time...

I copy/paste the entire code from my file index.html:

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">


</script>
</head>
<body>
<script type="text/javascript">
function nextMsg() {
    if (messages.length == 0) {
        alert("redirecting");
    } 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();
</script>

<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
</html>

Thanks in advance :)

Upvotes: 6

Views: 1496

Answers (1)

p0d4r14n
p0d4r14n

Reputation: 681

Just change the order dont execute javascript at the beginning of your code always at the end and/or use document ready to be sure dom is loaded before executing js

<h1>Hello world!</h1>
    <p>Here is a message: <span id="message"></span></p>

<script>
     $(document).ready(function() {
function nextMsg() {
    if (messages.length == 0) {
        alert("redirecting");
    } 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();
});
</script>

Upvotes: 3

Related Questions