Cycle css div left with an array in javascript - javascript

This code goes direct to the last position of the array, what I want is to iterate or cycle through them all and at the last position go to the first of the array. I'm tried something else but it gave me an error parsing left in firefox. This is the code fiddle Demo.
Body:
<div id="placeDiv">ok</div>
<script>
var times = ["2px","2000px","200px","12px","20px","200px","2000px"];
var move=times;
var i=0;
if(i == move.length-1)
{i=0;}
else
{i=i+1;};
document.getElementById("placeDiv").style.left=move[i];
</script>
Css:
<style>#placeDiv{position:absolute;top:0px;width:100px;height:100px;background-color:purple}</style>
This code does not work:
var times = [];
for (var i = 0; i < 30000; i++) {
times.push("\""+i+"px\"");
} var move=times;
if(i == move.length-1)
{i=0;}
else
{i=i+1;};
document.getElementById("placeDiv").style.left=move[i];
With the code above I get a this error in firefox:
Error in parsing value for 'left'. Declaration dropped.

You will need to use setTimeout here. For example:
var times = ["2px", "20px", "30px", "12px", "20px", "200px", "20px"],
move = 0,
div = document.getElementById("placeDiv");
setTimeout(function next() {
div.style.left = times[move++ % times.length];
setTimeout(next, 1000)
}, 1000);
To cycle an array values it's very useful to use % operator.
Demo: http://jsfiddle.net/m6w6K/1/
Or with setInterval:
function makeMove() {
div.style.left = times[move++ % times.length];
}
setInterval(makeMove, 1000);
Demo: http://jsfiddle.net/m6w6K/4/

Try this:
function sleep(millis, callback) {
setTimeout(function()
{ callback(); }
, millis);
}
var times = ["2px","20px","20px","12px","20px","2000px","20px"];
var move=times;
var i=0;
(function foobar_cont(){
if(i == move.length-1) {i=0;}
else {i=i+1;};
document.getElementById("placeDiv").style.left=move[i];
sleep(1000, foobar_cont);
})();
Demo

I've taken dfsq's original answer, and added some spice to it:
$(div).animate({left: times[move++ % times.length]}, 500);
Demo

There was a syntax error in your codes ... Link . It works very well for me but .. the "times" or transition is not visible to the user .. cause its to fast. :)
<div id="placeDiv">ok</div>
<script>
var times = ["2px","2000px","200px","12px","20px","200px","2000px"];
var move=times;
var i=0;
if(i == move.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv").style.left=move[i];
</script>

Related

Having real trouble combining 2 JS

I am struggling combining two JS into one… I try and try in the JSFiddle but can not really understand the console erros…
I am trying to have a background-color that changes combined with a changing background .svg in a div…
$(document).ready(function() {
//Initializing
var i = 0;
var images = []; //array
var time = 3000; // time in millie seconds
//images
images[0] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_1.svg)";
images[1] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_2.svg)";
images[2] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_3.svg)";
images[3] = "url(http://www.cyrill-kuhlmann.de/verve/img/logo_4.svg)";
//function
function changeImage() {
var el = document.getElementById('header');
el.style.backgroundImage = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout('changeImage()', time);
}
window.onload = changeImage;
$(function setbackground() {
window.setTimeout( "setbackground()", 2000);
var index = Math.round(Math.random() * 4);
var ColorValue = "FA89CB";
if(index == 1)
ColorValue = "FAED96";
if(index == 2)
ColorValue = "D27DFA";
if(index == 3)
ColorValue = "6CFA64";
if(index == 4)
ColorValue = "8370FA";
document.getElementsByTagName("body")[0].style.backgroundColor = "#" + ColorValue;
});
});
Here's my fiddle:
http://jsfiddle.net/gmck02ru/1/
does somebody have a clue – i guess I am not really understanding what I am doing here so far...
Help please!
The issue is because the syntax you've used to define the setbackground() function is incorrect. You've placed it inside a jQuery object. That function is also never called. You should define it as a standalone function and invoke it when the page loads.
In addition there's a few improvements you can make to the logic.
Use addEventListener() over setting the onclick or other onX event properties.
Declare the elements of the array at the same time as you define the array itself.
Use an array to hold the background colours instead of hard-coding an if statement.
Use the modulo operator when incrementing the counter to save having to write logic to reset to 0
If you want to repeatedly update the background colour, as you do for the images, place the setTimeout() call within the setbackground() function.
Use document.body directly instead of getting it by tag name
$(document).ready(function() {
let i = 0;
let images = [
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_1.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_2.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_3.svg)",
"url(http://www.cyrill-kuhlmann.de/verve/img/logo_4.svg)"
];
let backgroundColours = ['#FAED96', '#D27DFA', '#6CFA64', '#8370FA']
function changeImage() {
let el = document.getElementById('header');
el.style.backgroundImage = images[i];
i = ++i % (images.length - 1)
setTimeout(changeImage, 3000);
}
changeImage();
function setbackground() {
let index = Math.round(Math.random() * 4);
document.body.style.backgroundColor = backgroundColours[index];
setTimeout(setbackground, 2000);
}
setbackground();
});
Working jsFiddle - see the demo in the fiddle as the images are on an insecure domain so cannot be called from SO.

Trying to change div by class every 5 seconds jquery

Good morning,
I am trying to create an array of classes and with a 5 second interval, I would like to add and remove class replacing the current div. This is for a carousel where I currently have the background image changing at this time. I would now like to make my descriptive text alternate in the same way. Can anyone help?
I was thinking an if statement checking the current background could work. Howver I get this error: 'unexpected token {'
$(document).ready(function(){
/* H E A D E R C A R O S U E L */
$(function() {
var headCarosuel = $(".headCarosuel");
var backgrounds = new Array(
"url('./img/backgroundVinny1.jpg')","url('./img/backgroundVinny2.jpg')"
);
var current = 0;
function nextBackground() {
$(".headCarosuel").css("background", backgrounds[current = ++current % backgrounds.length]);
setTimeout(nextBackground, 5000);
}
setTimeout(nextBackground, 5000);
$(".headCarosuel").css("background", backgrounds[0]);
if(backgrounds = $("url('./img/backgroundVinny1.jpg')").css() {
$('.headCarosuelText').removeClass('description2').addClass('description1');
}
else {
$('.headCarosuelText').removeClass('description1').addClass('description2');
}
});
});
To do something every 5 seconds in javascript, you can use setInterval, for instance:
setInterval(function(){
//your code
,5000);
This will run the code every 5000ms or 5s.
Maybe something like this:
var classes = [
'class1',
'class2',
'class3',
'class4',
'class5'
]
var classIndex = 0;
function loopClasses() {
var currentClass = classes[classIndex];
// loop through classes and remove from element
for (var i = 0; i < classes.length; i++) {
$('.element').removeClass(classes[i]);
}
// add current class to element
$('.element').addClass(currentClass);
// advance or reset loop counter
classIndex = (classIndex + 1) % classes.length
}
setInterval(loopClasses, 5000);

Play Boostrap Popover on loop

DEMO: http://jsfiddle.net/0s730kxx/
I'm trying to open Bootstrap Popover to auto-open on loop but so far I've have manage only to auto-play once.
HTML:
<div class="container">
Hover Left |
Hover Right |
Click Me
</div>
JS:
$(document).ready(function(){
var time = 1000;
var len = $('.myclass').length;
var count = 0;
var fun = setInterval(function(){
count++;
if(count>len){
clearInterval(fun);
}
$('.p'+count).popover('show');
if(count>1){
var pre = count-1;
$('.p'+pre).popover('hide');
}
}, time);
});
Could anyone help? I want it on loop so it plays forever or atleast 10 or 20 times.
Modify javascript part of your fiddle like this:
$(document).ready(function(){
var time = 1000;
var len = $('.myclass').length;
var count = 0;
var fun = setInterval(function(){
count++;
if(count>len){
$('.p'+(count-1)).popover('hide');
count = 1;
//clearInterval(fun);
}
$('.p'+count).popover('show');
if(count>1){
var pre = count-1;
$('.p'+pre).popover('hide');
}
}, time);
});
Since you are not clearing the interval in this modified snippet, it will run forever as you expected.
Thats because you have added line
if(count>len){
clearInterval(fun);
}
After showing them 1 time count is 3 and clearInterval(fun) is called
which terminates further call to function fun().
Original comment: You can't clear the interval and expect the loop to continue! Instead of clearing set the count back to 0. But you'll also need to remember to hide the last popover.
var fun = setInterval(function(){
count++;
$('.p' + count).popover('show');
if(count > 1){
$('.p' + (count - 1)).popover('hide');
}
if(count > len){
count = 0;
}
}, time);
Here is a fiddle: http://jsfiddle.net/89gcqnfm/
Simplicity and modular arithmetic are your friends:
$(document).ready(function(){
var time = 1000;
var eles = $('.myclass');
var count = 0;
var fun = setInterval(function(){
if(eles.length < 1)
return (console.log("No elements found!")&&!1) || clearInterval(fun);
eles.eq(count%eles.length).popover('hide');
eles.eq(++count%eles.length).popover('show');
}, time);
});
https://jsfiddle.net/L2487dfy/

Change img src every second using Jquery and Javascript

I have been trying to write a script that changes an image src every two seconds based on a list.
So, everything is inside a forloop that loops over that list:
$(document).ready(function() {
var lis = {{dias|safe}}; <----- a long list from django. This part of the code works fine.
for (i=0; i<lis.length; i++){
src_img = lis[i][1];
var timeout = setInterval(function(){
console.log(src_img)
$("#imagen").attr("src", src_img);
}, 2000)
}
});
It doesn't work, the console logs thousands of srcs that correspond to the last item on the list. Thanks a lot for your help.
you don't need to run cycle in this case, you just save "pointer" - curentImage and call next array item through function ever 2 sec
var curentImage = 0;
function getNextImg(){
var url = lis[curentImage];
if(lis[curentImage]){
curentImage++;
} else {
curentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
var curentImage = 0;
var length = lis.length;
function NewImage(){
var url = lis[curentImage];
if(curentImage < length){
currentImage++;
}
else{
currentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
PS: Better than the previous one, Checks for lis length and starts from first if you reach end.
You need something like this
$(document).ready(function() {
var index = 0;
setInterval(function(){
src_img = lis[index++ % lis.lenght][1]; // avoid arrayOutOfBounds
$("#imagen").attr("src", src_img);
}, 2000)
});

jQuery animation for each element

I do not have much experience in animation on Jquery. I want to make a simple animation that will highlight my text line by line with the possibility of stopping. I know how to do something like this for one line but I have no idea how to deal with loop.
here is my code:
var lines = $('#page')[0].getClientRects();
for (var i=0, max = lines.length; i < max; i++)
{
$('#under_liner')
.queue(function() {
$(this).css('top', lines[i].bottom).dequeue();
})
.animate({
width: lines[i].right - lines[i].left
}, 1000 )
.queue(function() {
$(this).css('width', 0).dequeue();
});
}
and jsfiddle http://jsfiddle.net/mz03kfua/2
I don't know if this is exactly what you are looking for, but here's how I'd do it.
Make a function that does the underlining
Make a recursive call on animation callback
Create a global variable to keep count of the current underlined line
Add a boolean that stops the function when false
var lines = $('#page')[0].getClientRects();
var play = true;
var index = 0;
underlineLine();
$('button').click(function(){
play = !play
if(play){
underlineLine()
$(this).html("STOP")
}else{
$(this).html("CONTINUE")
}
})
function underlineLine(){
if(index >= lines.length) return
if(play){
$('#under_liner').css('top', lines[index].bottom).dequeue();
$('#under_liner').css('width','0px');
$('#under_liner').animate({
width: lines[index].right - lines[index].left
}, 1000, function(){
underlineLine(index++)
})
$('#under_liner').css('width', 0).dequeue();
}
}
HERE IS A FIDDLE WITH THE CODE.
Hope it helps.
http://jsfiddle.net/mz03kfua/4/
var lines = $('#page')[0].getClientRects();
var current = 0;
var element;
function animateLine() {
if(typeof lines[current] !== "object") {
return;
}
var line = lines[current];
element = jQuery("<div />", {"class": "under_liner"}).prependTo("#page");
element.css({top: line.bottom}).animate({width: line.width}, 1000, function() {
current++;
animateLine();
});
}
function stopLine(e) {
e.preventDefault();
element.stop(true);
}
jQuery(".stop").click(stopLine);
animateLine();

Categories

Resources