Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 242
Rajesh Muntari Avatar asked Dec 15 '14 20:12

Rajesh Muntari


People also ask

How to change text after some time in jQuery?

To change text inside an element using jQuery, use the text() method.

How to change text of div using jQuery?

To replace only text inside a div using jQuery, use the text() method.

How to add after in jQuery?

jQuery insertAfter() MethodThe insertAfter() method inserts HTML elements after the selected elements. Tip: To insert HTML elements before the selected elements, use the insertBefore() method.


1 Answers

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>
like image 147
p0d4r14n Avatar answered Oct 05 '22 02:10

p0d4r14n