Javascript Text Slideshow - javascript

I am trying to add text into a div using JavaScript and/or jQuery and then have that text change to different text every 10 seconds -- so somewhat like a slideshow of just plain text. Here's my code:
<div id="textslide"><p></p></div>
<script>
var quotes = new Array();
quotes[0] = "quote1";
quotes[1] = "quote2";
quotes[2] = "quote3";
quotes[3] = "quote4";
quotes[4] = "quote5";
var counter = 0;
while (true) {
if (counter > 4) counter = 0;
document.getElementById('textslide').firstChild.innerHTML = quotes[counter];
counter++;
setTimeout( // not sure what to put here, 500); // Want to delay loop iteration
}
</script>

HTML:
<div id="textslide"><p></p></div>
JavaScript/jQuery:
var quotes = [
"quote1",
"quote2",
"quote3",
"quote4",
"quote5",
];
var i = 0;
setInterval(function() {
$("#textslide").html(quotes[i]);
if (i == quotes.length) {
i = 0;
}
else {
i++;
}
}, 10 * 1000);
Working demo here

Use a function and call it on body onload
<html>
<head>
<script>
var counter = 0;
function changeText()
{
var quotes = new Array();
quotes[0] = "quote1";
quotes[1] = "quote2";
quotes[2] = "quote3";
quotes[3] = "quote4";
quotes[4] = "quote5";
if (counter > 4)
{
counter = 0;
}
document.getElementById("textslide").innerHTML = quotes[counter];
setTimeout(function(){changeText()},10000);
counter ++;
}
</script>
</head>
<body onload="changeText();">
<p id="textslide"></p>
</body>
</html>

Here is a suggestion with plain JS
function loop() {
if (counter > 4) counter = 0;
document.getElementById('textslide').firstElementChild.innerHTML = quotes[counter];
counter++;
setTimeout(loop, 500);
}
loop();
Demo here
If you want to use jQuery you can use this: $('#textslide p:first').text(quotes[counter]);
Demo here

Instead of while, use:
setInterval(function () {
//do your work here
}, 10000);

Related

error on trying to change image in sequence from list JavaScript

I have a list:
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
I made a code which attempts at displaying image1 when the page loads but for ever 3 seconds the image changes to the next image in the list. However when the code was ran it was stuck on image1 and did not change in the next 3 seconds.
This is my JavaScript code so far:
<html>
<body>
<body onload = "myFunction()">
<img src ="image1.png" id = "target" >
<script language="javascript">
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 4) {
counter = 0
}
target = document.getElementById ("target").src = images[counter];
setTimeout("myFunction", 3000)
}
window.onLoad = function(){
myFunction();
}
</script>
</body>
</html>
I have seen similar codes but the answers answered did not meet my specification.
You can use setInterval (passing a function rather than a string) instead of recursively calling setTimeout. Also note that your counter logic can be greatly simplified with the use of the modulo (%) operator:
<html>
<body>
<img src="image1.png" alt="image1.png" id="target">
<script language="javascript">
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
var target = document.getElementById("target")
setInterval(function myFunction() {
counter = (counter + 1) % images.length
target.src = target.alt = images[counter]
}, 3000)
</script>
</body>
</html>
In setInterval, you need to pass the function myFunction as parameter, not the function name "myFunction":
Change it to this:
setTimeout(myFunction, 3000);
setTimeout - will work only one time
setInterval - will continue always
<html>
<body>
<img src ="logo.png" id = "target" >
<script language="javascript">
var counter = 0;
var images = ["logo.png", "222.jpg"];
function myFunction() {
counter++;
if (counter > 1) {
counter = 0
}
target = document.getElementById("target").src = images[counter];
}
function my2(){
setInterval("myFunction()", 1000);
}
window.onload = function(){
my2();
}
</script>
</body>
</html>
Expanding on what others have mentioned already.
It's window.onload - not window.onLoad - Casing is important
Update to
setTimeout(myFunction, 3000);
Place that in your window.onload
JS:
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 4) {
counter = 0
}
target = document.getElementById ("target").src = images[counter];
}
window.onload = function(){
setTimeout(myFunction, 3000)
}
You can use setInterval instead of setTimeout
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 3) {
counter = 0
}
target = document.getElementById("target").src = images[counter];
}
setInterval(myFunction, 3000);
JSFiddle

How to make my script pause after reaching a certain condition for 1000ms

I've got a setInterval script that repeats logging "Hello world" 10 times.
I would like to make it stop for 1 second after repeating 10 times, then starting again and doing the process for ever.
here is what I have:
var i = 0;
var x = setInterval(function(){
console.log("Hello world");
i++;
if(i >= 10){
i = 0;
stopInterval()
}
},1000);
var stopInterval = function(){
clearInterval(x);
setTimeout(function(){
//restart the interval, but how do I do???
},1000);
};
However, it says stopInterval is not defined and I thought it was
So you need to use clearInterval and use the id that is returned from setInterval to clear it.
function myTimer() {
var i = 0,
interval = setInterval(function(){
console.log("Hello world");
i++;
if(i >=10){
clearInterval(interval);
window.setTimeout(myTimer, 1000);
}
},100);
}
https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Timers
just with setTimeout and Recursion DEMO
var i = 1;
var delay = 500;
function callMe() {
console.log("Hello World"+i);
document.getElementById("pri").innerHTML = "Hello World " + i;
if (i == 11) {
i = 1;
delay = 1000;
console.log("......Restart");
document.getElementById("pri").innerHTML = "......Restart";
} else {
delay = 300;
}
setTimeout(callMe, delay);
++i;
}
window.onload = callMe;
<div id="pri"></div>

Writing Text Effect with jquery

I am use this code for Writing Text Effect:
<script type="text/javascript">
$(document).ready(function () {
function changeText(cont1, cont2, speed) {
var Otext = cont1.text();
var Ocontent = Otext.split("");
var i = 0;
function show() {
if (i < Ocontent.length) {
cont2.append(Ocontent[i]);
i = i + 1;
};
};
var Otimer = setInterval(show, speed);
};
$(document).ready(function () {
changeText($("#TypeEffect p"), $(".p2"), 150);
});
});
</script>
but its not working for multiline, I use this code:
changeText($("#TypeEffect p, #TypeEffect br"), $(".p2"), 150);
so, its not working.
please help me for Writing Text Effect in multi line.
Try
$(document).ready(function () {
function changeText(cont1, cont2, speed) {
var contents = $(cont1).contents().map(function () {
if (this.nodeType == 3) {
if ($.trim(this.nodeValue).length) {
return this.nodeValue.split("")
}
} else {
return $(this).clone().get();
}
}).get();
var i = 0;
function show() {
if (i < contents.length) {
cont2.append(contents[i]);
i = i + 1;
} else {
clearInterval(Otimer)
}
};
var Otimer = setInterval(show, speed);
};
$(document).ready(function () {
changeText($("#TypeEffect p"), $(".p2"), 150);
});
});
Demo: Fiddle
Try this:
$("[class*=autoWrite]").each(function(e){
autoWriteText($(this));
})
function autoWriteText(elm){
var clas = elm.attr("class");
clas = clas.split("-");
var speed = clas[1];
var delay = clas[2];
var txt = elm.html();
elm.html("");
setTimeout(function(){
elm.fadeIn("fast");
txt = txt.split("");
var txtI = 0;
var html = "";
var intrvl = setInterval(function(){
html = html + txt[txtI] ;
elm.html(html + "_");
txtI = txtI + 1;
if(txtI == txt.length){
clearInterval(intrvl);
}
},speed);
},delay)
}
.autoWriteText{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<h5 class="autoWrite-10-0" >This element will write a <b>letter every 10 milliseconds</b> in this box, with a <b>delay of 0 milliseconds</b>.</h5>
<hr>
<h5 class="autoWrite-50-1000" >This element will write a <b>letter every 50 milliseconds</b> in this box, with a <b>delay of 1 second</b>.</h5>
<hr>
<h5 class="autoWrite-200-3000" >This element will write a <b>letter every 200 milliseconds</b> in this box, with a <b>delay of 3 second</b>.</h5>
<hr>
<h5 class="autoWrite-500-5000" >This element will write a <b>letter every 500 milliseconds</b> in this box, with a <b>delay of 5 second</b>.</h5>
<hr>

setInterval won't get out of loop

The following javascript code takes randomly selected value from a array and types it in the input box. I've used jquery. I want to end setInterval "zaman2", so after It ends I can retype the next random string to the input box. But the loop doesn't end and gets stuck. How can I solve this?
Link to jsFiddle: http://jsfiddle.net/AQbq4/4/
var dersler = [...very long list...];
var zaman = setTimeout(function() {
var yeniDers = dersler[Math.floor(Math.random()*dersler.length)];
sayac = 0;
var zaman2 = setInterval(function() {
var harf = yeniDers.slice(0,(sayac+1));
sayac++;
$('#main-search').attr('placeholder', harf).typeahead({source: dersler});
if (sayac == yeniDers.length) {
clearInterval(zaman2);
}
},450);
},2000);
Don't you mean
DEMO
var tId, tId2;
function show() {
var ran = arr[Math.floor(Math.random()*arr.length)];
cnt = 0;
tId = setInterval(function() {
var char = ran.slice(0,(cnt+1));
cnt++;
$( '#main-search' ).attr('placeholder', char);
if (cnt == ran.length) {
clearInterval(tId);
tId2=setTimeout(show,2000);
}
},450);
}
show();

How to stop my javascript countdown?

How can I stop my javascript function when countdown = 0?
JS:
var settimmer = 0;
$(function(){
window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
}, 1000);
});
HTML:
<b id="show-time">20</b>
For one thing remove those evals. They don't do anything.
Then all you have to do is clear the timer when it reaches zero.
$(function(){
var timer = setInterval(function() {
var timeCounter = parseInt($("b[id=show-time]").text());
$("b[id=show-time]").text(--timeCounter); // remove one
if(!timeCounter) clearInterval(timer);
}, 1000);
});
It is easy! When you call setInterval it return an ID, so you can destroy the interval later. To destroy it you must use clearInterval(id), and voilà!
It works like this:
// Activate timer
var iv = window.setInterval(...);
// Deactive timer
window.clearInterval(iv);
Also you should use parseInt() instead of eval():
$(function() {
// Read the start value once and store it in a variable
var timeCounter = parseInt( $("b[id=show-time]").text() );
// Active the counter
var iv = window.setInterval(function() {
// Decrement by one and write back into the document
$("b[id=show-time]").text(--timeCounter);
// Check if counter == 0 -> stop counting
if (0 == timeCounter) {
window.clearInterval(iv);
// ...do whatever else needs to be done when counter == 0 ..
}
}, 1000);
});
Example:
var i = 0,
pid = setInterval(function() {
if (++i > 10)
clearInterval(pid);
}, 1000);
Based on what you wanted for your code ...
$(function() {
var el = document.getElementById('show-time'),
pid = setInterval(function() {
// (s - i) coerces s to Number
var t = el.innerHTML - 1;
el.innerHTML = t;
if (t < 1)
clearInterval(pid);
}, 1000);
});
Keep in mind that JS won't be 100% accurate with its timing.
Pasted code below or see the fiddle: http://jsfiddle.net/raHrm/
<script type="text/javascript">
$(function(){
var settimmer = 0,
timeCounter = $("#show-time").html(),
updateTime = timeCounter;
(function countDown() {
timeCounter = $("#show-time").html();
updateTime = parseInt(timeCounter)-1;
$("#show-time").html(updateTime);
if ( updateTime ) {
setTimeout(countDown, 1000);
}
})();
});​
</script>
Set the timer to a variable, then use clearInterval in-order to stop the loop. As for catching the end, use a simple conditional:
$(function(){
var elem=$('strong[id="show-time"]'),settimmer=0,updateTime,t;
t=window.setInterval(function() {
updateTime=parseFloat(elem.html(),10)-1;
if(updateTime==0) {
window.clearInterval(t);
elem.html('Done!');
} else {
elem.html(updateTime);
}
},1000);
});
Then in the HTML:
<strong id="show-time">20</strong>
The <b> tag is depreciated, try to avoid using it. Also, there is no reason to eval() the HTML you are getting from the element; a simple parseFloat() works just fine.

Categories