for(){} and setInterval() doesn't work - javascript

I want to picture 5s change next picture, but I can't make this work.
<div class="g-carousel" id="m-carousel">
<img src="imag/banner1.jpg" >
<img src="imag/banner2.jpg" >
<img src="imag/banner3.jpg" >
<div class="button">
<i class="checked"></i><i></i><i></i>
</div>
</div>
<script type="text/javascript">
function showpic() {
var carousel = document.getElementById("m-carousel")
var pciture = carousel.getElementsByClassName("pciture");
for (var i=0 ; i < pciture.length; i++)
if (i>2) i=0;
pciture[i].style.display="none";
pciture[i+1].style.display="block";
}
window.onload=function function_name(argument) {
setInterval("showpic()",5000);
}
</script>

Working jsfiddle
function showpic() {
var carousel = document.getElementById("m-carousel");
var carouselLength = carousel.getElementsByTagName("a").length;
var pciture = carousel.getElementsByClassName("pciture");
if (i>=carouselLength-1){
pciture[i].style.display="none";
i=0;
pciture[i].style.display="block";
i--;
}else{
pciture[i].style.display="none";
pciture[i+1].style.display="block";
}
i++;
}
var i = 0;
setInterval(showpic,2000);

You need to have a global counter:
var counter = 0;
function showpic() {
var carousel = document.getElementById("m-carousel")
var pciture = carousel.getElementsByClassName("pciture");
// Hide all the pictures.
for (var i=0 ; i < pciture.length; i++)
{
pciture[i].style.display="none";
}
// Show the picture based on the counter.
pciture[counter].style.display="block";
// Increment the counter ready for next time.
counter++;
// Check if the counter needs to loop back.
if(counter >= pciture.length)
counter = 0;
}
window.onload = function() {
setInterval(showpic, 5000);
}
Here is a working example

Maybe it would help if you change
window.onload=function function_name(argument) {
to
window.onload=function(argument) {
Hope that helps.
Regards
P.S. Live long and prosper :-)

Related

i want to make a counter function dynamic in javascript

i have called a counter function in loop. there are 4 items per page.
i have passed $i in loop and written 4 functions
but if i changed pagination limit to 5 or 10 ,it is not a good solution
anybody can help me to solve it?
here is my div in foreach loop where l called function
<div class="tick"
data-value="'.$start.'"
data-did-init="handleTickInit'.$i.'">
<div data-layout="horizontal center"
data-repeat="true"
">
<div data-view="swap"
></div>
</div>
handleTickInit'.$i is function
function handleTickInit2(tick) {
var value = tick.value;
var target = 0;
var timer = Tick.helper.interval(function() {
// have we reached the donation target yet?
if (value>=target) {
// no, keep going
var realprice=$("#realprice-2").val();
var startdate=$("#startdate-2").val();
var currenttime = Math.round((new Date()).getTime()/1000);
var stepsec=$("#stepsec-2").val();
// alert(stepsec);
var diffsec=currenttime-startdate;
var loss=diffsec*stepsec;
var start=realprice-loss;
tick.value = start.toFixed(4);
$("#saveval-2").val(start);
// value= tick.value ;
}
else {
// yes, stop the timer
timer.stop();
}
}, 1000);
}
please give some solution to make it dynamic
Try this
var handleTickInit = {};
var num = 5;
var handleFunc = function() {
return function (tick) {
var value = tick.value;
var target = 0;
var timer = Tick.helper.interval(function() {
// have we reached the donation target yet?
if (value>=target) {
// no, keep going
var realprice=$("#realprice-2").val();
var startdate=$("#startdate-2").val();
var currenttime = Math.round((new Date()).getTime()/1000);
var stepsec=$("#stepsec-2").val();
// alert(stepsec);
var diffsec=currenttime-startdate;
var loss=diffsec*stepsec;
var start=realprice-loss;
tick.value = start.toFixed(4);
$("#saveval-2").val(start);
// value= tick.value ;
}
else {
// yes, stop the timer
timer.stop();
}
}, 1000);
}
}
for(var i = 0; i< num; i++){
handleTickInit[i] = handleFunc();
}
console.log(handleTickInit);
All your handle tick functions are in handleTickInit;

Finishing a sub-function with setTimeout loop before function

I've been wrestling with a timing issue in my code for a few nights now, and can't come up with the correct solution.
Psuedo code description:
//event listener on button trigger a die roll each time it is clicked
// call animation function
//generate random values x number of times
//display each result with setTimeout
//run code to determine final "settled upon" value and display results
HTML:
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<head>
<title>Make Cards</title>
</head>
<body>
<p>Total:<span id="total"></span></p>
<div id="contain">
<div class="die"></div>
<div class="die"></div>
<div class="die"></div>
<div class="die"></div>
<div class="die"></div>
<div class="die"></div>
<br>
<button id="rollBtn">Roll</button>
<input type="number" value = "1" min="1" max="6" id = "numDice">
</div>
</body>
</html>
Javascript:
var diceValue = ["&#9856", "&#9857", "&#9858", "&#9859", "&#9860",
"&#9861"];
var dice = document.querySelectorAll(".die");
// select number of dice
var numDice = document.querySelector("#numDice");
// convert string to value
var newNumDice = Number(numDice.value);
var roll = document.querySelector("#rollBtn");
var total = document.querySelector("#total");
// make animation function
// call animation function
init();
function init(){
displayDice();
}
//THIS IS THE BUTTON LISTERNER
roll.addEventListener("click", function(){
//THIS SHOULD RUN BEFORE THE REST OF THE FUNCTION (BUT DOESN'T SEEM TO)
animate();
var subTotal = 0;
for (var i = 0; i < newNumDice; i++){
var value = generateRandomDice()
dice[i].innerHTML = diceValue[value];
subTotal = subTotal + (value+1);
total.innerHTML = subTotal;
}
for (var i = 0; i < 6; i++){
dice[i].style.color = "black";
}
})
numDice.addEventListener("click", function(){
total.innerHTML = "-";
newNumDice = Number(numDice.value);
resetDice();
displayDice();
// console.log(Number(numDice.value));
})
function resetDice(){
for (var i = 0; i < diceValue.length; i++){
dice[i].innerHTML = "";
}
}
// only display chosen number of dice
function displayDice(){
for (var i = 0; i < newNumDice; i++){
dice[i].innerHTML = diceValue[i];
}
}
function generateRandomDice(){
var dieSide = Math.floor(Math.random() * 6);
return dieSide;
}
//ATTEMPT AT WRITING CODE FOR ANIMATION
function animate(){
for (var i = 0; i < 50000; i++){
var ani = setTimeout(rolling, 650);
}
}
function rolling(){
for (var i = 0; i < newNumDice; i++){
var value = generateRandomDice()
dice[i].innerHTML = diceValue[value];
dice[i].style.color = "grey";
}
}
Not sure what is going on, but it appears to me that the animate(); code is not run until the rest of eventListener is finished. Any help is great, thank you.
The issue is that you are waiting for asynchronous code to finish before you execute synchronous code. Every time you call setTimeout, it is storing the function to call for when it's ready to be called (which is 650 ms from 'now'!).
To fix, you can await for your animation to finish. Here's how I got it working on your codepen:
Change animate to:
function animate() {
return new Promise((resolve, reject) => {
for (let i = 0; i < 50000; i++) {
setTimeout(() => {
rolling();
if(i == 49999)
resolve();
}, 650);
}
});
}
and then you can await for the Promise to resolve by changing your click listener to this:
roll.addEventListener("click", async function() {
await animate();
var subTotal = 0;
for (var i = 0; i < newNumDice; i++) {
var value = generateRandomDice();
dice[i].innerHTML = diceValue[value];
subTotal = subTotal + (value + 1);
total.innerHTML = subTotal;
}
for (var i = 0; i < 6; i++) {
dice[i].style.color = "black";
}
});
The result showing afterward was correct for me.
Hope that helps!

How to ssign Variable with div element's name

So I got multiple divs with different images embedded. Each one has its unique name attributes. I'm trying to apply the hover effect to each divs by changing the image source. I don't want to write multiple scripts, rather I'm trying to write a just one block of script that would effect every div.
<div id="div1" >
<img id="img1" name="img1" src="img1_up.jpg" />
</div>
<div id="div2">
<img id="img2" name="img2" src="img2_up.jpg" />
</div>...and so on
Now here is the script that I currently have for the rollover effects
<script>
var var1 = document.getElementById("div1");
var1.addEventListener("mouseover", changeImage1);
var1.addEventListener("mouseout", restoreImage1);
function changeImage1() {
document.getElementById("img1").src = "img1_ro.jpg";
}
function restoreImage1() {
document.getElementById("img1").src = "img1_up.jpg";
}
var var2 = document.getElementById("div2");
var2.addEventListener("mouseover", changeImage2);
var2.addEventListener("mouseout", restoreImage2);
function changeImage2() {
document.getElementById("img2").src = "img2_ro.jpg";
}
function restoreImage2() {
document.getElementById("img2").src = "img2_up.jpg";
}...and so on
</script>
I would like to use the name attributes from each images to create dynamic code to apply to all images. Here is what I have in mind but not sure the exact way to write it. PLEASE HELP
...
var dynamicVar = ????
dynamicVar.addEventListener("mouseover", changeImage();
dynamicVar.addEventListener("mouseout", restoreImage();
function changeImage() {
document.getElementById(dynamicVar).src = dynamicVar + "_ro.jpg";
}
function restoreImage() {
document.getElementById(dynamicVar).src = dynamicVar + "_up.jpg";
}
You can use loop to add event, don't need to specify id for each div:
var inputs = document.getElementsByTagName("div");
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].id.indexOf('div') >= 0) {
inputs[i].addEventListener("mouseover", changeImage);
inputs[i].addEventListener("mouseout", restoreImage);
}
}
function changeImage(){
var tmpStr = this.id;
var divIndex = tmpStr.substring(3, tmpStr.length);
document.getElementById("img" + divIndex).src = divIndex + "_ro.jpg";
}
function restoreImage(){
var tmpStr = this.id;
var divIndex = tmpStr.substring(3, tmpStr.length);
document.getElementById("img" + divIndex).src = divIndex + "_up.jpg";
}
See on fiddle: Link
try this
var parent = document.getElementById("parent");
var childs = parent.getElementsByTagName('div');
for (var i = 0; i < childs.length; i++) {
(function () {
var e = childs[i];
e.addEventListener("mouseover", function () {
changeImage(e);
});
e.addEventListener("mouseout", function () {
restoreImage(e);
});
}());
}
function changeImage(element) {
var imgs = element.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
alert(imgs[i].id);
}
}
function restoreImage(element) {
var imgs = element.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
imgs[i].src = img_ro;
}
}
you can check this fiddle

javascript clear timeouts in loop

The code below appends numbers in sequence from 1 to 10 when the start button is clicked. I'd like to use clearTimeout to cancel the operation when the stop button is clicked.
It seems to me that a dynamic variable must be created (where x is currently assigned the doSetTimeout function), but I have not yet found a way to do so. Any suggestions?
Thanks!
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function doSetTimeout(func, func_param, time) {
setTimeout(function(){func(func_param);}, time);
}
function createNode(base) {
var node = document.createElement("p");
var writeI = base + "";
var textnode = document.createTextNode(writeI);
node.appendChild(textnode);
document.body.appendChild(node);
}
$(document).ready(function() {
$("#start").click(function() {
for (var i = 1; i <= 10; i++) {
var time = i*1000;
var x = doSetTimeout(createNode, i, time);
}
});
});
</script>
</head>
<body>
<button id="start">Start</button>
<button id="stop">Stop</button>
</body>
Get the return value of setTimeout, keep it in a list, and clear it when you click stop.
function doSetTimeout(func, func_param, time) {
return setTimeout(function(){func(func_param);}, time);
}
$(document).ready(function() {
var timeouts = [];
$("#start").click(function() {
for (var i = 1; i <= 10; i++) {
var time = i*1000;
timeouts.push(doSetTimeout(createNode, i, time));
}
});
$("#stop").click(function () {
for (var i = 0; i <= timeouts.length; i += 1) {
clearTimeout(timeouts[i]);
}
});
});
This might also clear timeouts that have already finished, but I doubt that's really very important.

for loop an argument in function

I was doing this code but it will take time because it will be h1 up until h24 so i decided to use a for loop but i don't know how..
this is my original code
function hover(h1,h2,h3,h4){
document.getElementById(h1).style.backgroundColor="orange";
document.getElementById(h2).style.backgroundColor="orange";
document.getElementById(h3).style.backgroundColor="orange";
document.getElementById(h4).style.backgroundColor="orange";
}
and i want to replace it something like this
function hover(
for(i = 1; i<=24; i++) {
document.write("h"+i+",");
}
)
but there is an error.. Please help me out.. Thank you
function hover() {
for(var i = 1; i < 25; i++) {
document.getElementById("h" + i).style.backgroundColor="orange";
}
}
If you could need more control, you could set the upper limit as a parameter, e.g.
function hover(limit) {
for(var i = 1; i <= limit; i++) {
document.getElementById("h" + i).style.backgroundColor="orange";
}
}
A call to hover(10); would change the background colour of h1 through h10.
There are several things wrong with the code you posted. I think I understand the problem you are trying to solve though. Try something like this:
function hover(eleId){
document.getElementById(eleId).style.backgroundColor="orange";
}
for(i=1; i<=24; i++){
hover("h"+i.toString());
}
Also note h1, h2, h3 all look like HTML tags. Check out getElementsByTagName.
You need to use Javascript's arguments object
function hover() {
var args = Array.prototype.slice.call(arguments);
var length = args.length;
for (var i = 0; i < length; i++) {
document.getElementById(args[i]).onmouseover =
function () { this.style.backgroundColor = "orange"; }
document.getElementById(args[i]).onmouseout =
function () { this.style.backgroundColor = "transparent"; }
}
}
jsFiddle Demo
HTML:
<div id="h1">A</div>
<div id="Hello">B</div>
<div id="box">C</div>
<div id="World">D</div>
JS Call:
hover("h1", "Hello", "box", "World");
Here is my suggestion :
<div id="h1">test</div>
<div id="h2">test</div>
<div id="h3">test</div>
<div id="h4">test</div>
script, notice the dummy variable
<script>
function hover(dummy){
for (var i=0; i<arguments.length; i++) {
var element = document.getElementById(arguments[i]);
element.onmouseover = function() {
this.style.backgroundColor="orange";
}
element.onmouseout = function() {
this.style.backgroundColor="white";
}
}
}
//hover('h1','h2','h3','h4');
for (var i=1;i<=24;i++) {
hover('h'+i);
}
</script>

Categories

Resources