Forum Moderators: open

Message Too Old, No Replies

How to make delayed loop of text

         

asco88

9:34 am on Aug 11, 2011 (gmt 0)

10+ Year Member



I would like to send a bunch of strings to a javascript script, and that script will change every few seconds a chosen text in the page, according to the strings.
For example, str1, str2, str3... Every 5 seconds i want a different str.
I dont think it requires any ajax, but if it is, i'd like to know how to do it.
Thank you in advance.

astupidname

7:01 am on Aug 12, 2011 (gmt 0)

10+ Year Member



Hi asco88, and welcome to webmasterworld!
The below should do the trick:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Some Title</title>
<script type="text/javascript">

//addThisEvent -utility function for setting event listeners
//cross-browser, and preserving 'this' within attachEvent.
//el may be a single html element as a DOM object, or the window object,
//type should be string name of event type ('on' prefix not required, so 'mouseover' or 'onmouseover' works fine)
//fn should be a function to set as an event handler
function addThisEvent(el, type, fn) {
var ename = type.replace(/^on/i, '');
if (el.attachEvent) { //IE
el.attachEvent('on'+ ename, function () {
return fn.call(el, window.event); //fixes IE's fudging of 'this' in attachEvent
});
} else if (el.addEventListener) { //Standard
el.addEventListener(ename, fn, false );
} else {
el["on"+ename] = fn;
}
}

addThisEvent(window, 'load', function () {
var i = 0,
frequency = 5000, //rate of change frequency, 1000 = 1 second
el = document.getElementById('rotatingTextParagraph'), //the html DOM element to show the text in
textArray = [
'first text string',
'second text string',
'third text string'
];
el.innerHTML = textArray[i++];
el.textRotationInterval = window.setInterval(function () {
if (i >= textArray.length) {
i = 0;
}
el.innerHTML = textArray[i++];
}, frequency);
});

</script>
</head>
<body>
<p id="rotatingTextParagraph"></p>
</body>
</html>

If anybody's wondering, how to post formatted code on webmasterworld [webmasterworld.com]
Do not copy formatted code on webmasterworld from IE, use other browser such as Firefox.

asco88

11:19 am on Aug 15, 2011 (gmt 0)

10+ Year Member



Thank you very much.
That was exactly what i was looking for.