Having real trouble combining 2 JS - javascript

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.

Related

How can I reuse a function properly?

I try to make 3 basic slideshow.
I made this code for the first one and wanted to use it on the other 2 as well with the New slideS() method and with some parameter changing.But it's not working,even the first function is'nt working if I put parameter in it.
Can somebody explain me why is this not working and how to fix it?Thanks beforehand!
var img = document.getElementById("asd");
var imgArr = ["1.jpg", "3.png", "3.png"];
var i = 0;
function slideS(a) {
a.src = imgArr[i];
if (i < imgArr.length - 1) {
i++;
} else {
i = 0;
}
setTimeout("slideS()", 1500);
}
slideS(img)
You could do something like this, using an object oriented approach:
function SlideShow(el, imagesArray, msDelay) {
this.el = el;
this.images = imagesArray;
this.delay = (msDelay) ? msDelay : 1000;
this.timer = null;
this.Run = function () {
var self = this;
var index = 0;
this.timer = setInterval(function(){
self.el.src = self.images[index++ % self.images.length];
}, this.delay);
}
this.Stop = function() {
this.timer = null;
}
}
var img = document.getElementById("asd");
var imgArr = ["1.jpg", "3.png", "3.png"];
var delay = 1500;
var ss = new SlideShow(img, imgArr, delay);
ss.Run();
...
ss.Stop();
Would that work for you? Then you are using pure functions and an object that can be used to start, stop, and manage any slide show.
I think you want like:
Remove setTimeout. And use setInterval:
setInterval(function(){
slideS(img)
},1500)
You could use a closure over the element and the array and use setInterval instead of setTimeout.
function slide(id, array) {
function swap() {
image.src = array[i];
i++;
i %= array.length;
}
var image = document.getElementById(id),
i = 0;
setInterval(swap, 1500);
}
slide('image1', ['http://lorempixel.com/400/200/', 'http://lorempixel.com/400/200/', 'http://lorempixel.com/400/200/']);
<image id="image1"></image>
I assume it works when the function doesn't take a parameter?
Then, the reason it would work with no parameter, but stop working with a parameter, is that the setTimeout tries to recursively call the function but doesn't pass a parameter. So you'd change that to
setTimeout(() => {slideS(a);}, 1500);
But then when you try to run multiple instances of this concurrently, you'll get into trouble because your'e using global variables. You'll need to use something more local (perhaps closures?) for your lcv, for example.
try this... you are making mistake at some places
var img = document.getElementById("asd");
var imgArr = ["1.jpg", "3.png", "3.png"];
var i = 0;
function slideS(a) {
a.src = imgArr[i];
if (i < imgArr.length - 1) {
i++;
} else {
i = 0;
}
setTimeout(() => slideS(a), 1500);
/* you need to pass function to setTimeout and pass refrence of image that's 'a' */
// or use function instead of arrow function
setTimeout(function() { slides(a) }, 1500);
}
slideS(img)
hope this helps..
You have to use setInterval instead of setTimeout
var img = document.getElementById("asd");
var imgArr = ["https://i.stack.imgur.com/lgt0W.png", "https://i.stack.imgur.com/X0fKm.png", "https://i.stack.imgur.com/YfPSD.png"];
var i = 0;
function slideS(a) {
a.src = imgArr[i];
if (i < imgArr.length - 1) {
i++;
} else {
i = 0;
}
}
slideS(img); //initial call to start it without having to wait for 1500 ms to pass
setInterval(function() {
slideS(img);
}, 1500);
<img id="asd">

Continuously fade in and out random pictures

I am trying to get make a function that will continuously fade in and out pictures that are randomly selected, so that the same picture doesn't come up twice. I can get it to fade out / change image / fade in once if it is clicked with
$("img").click(function() { CODE });
but I have to click the image each time, and I am getting stuck trying to make it into a function that is called when the page has loaded:
$(document).ready(function() {
$("img").fadeOut(2000, function() {
while (picPicker1 === picPicker2) {
picPicker2 = (Math.floor(Math.random() * 5) - 1);
}
var source = pics[picPicker2];
$("img").attr("src", source);
$("img").fadeIn(2000);
picPicker1 = picPicker2;
});
});
pics[] is an array with the web addresses of five different pictures. I also tried using setInterval, but that didn't work either. New to all of these languages so thank you in advance for your patience!
setInterval was the correct function to use. The code you've provided in your question is missing a closing });.
Here's some basic code that makes use of setInterval to change the image:
JQuery:
var pics = [
"https://placehold.it/350x150/ff0000",
"https://placehold.it/350x150/00ff00",
"https://placehold.it/350x150/0000ff",
"https://placehold.it/350x150/F2F5A9",
"https://placehold.it/350x150/FF00FF",
];
setInterval(function() {
var picPicker2 = (Math.floor(Math.random() * 5) + 1);
var source = pics[picPicker2];
$("img").fadeOut(500).attr("src", source).fadeIn(500);
}, 2000);
Note: The images will repeat occasionally, but the code I've provided is only a base for you to improve upon.
Fiddle Demo
You can either use setInterval(), for (x = 5; x > 0; x ++) {}, var x = 0; do {} while (x = 0);, or var x = 0; while (x = 0) {}.
$(document).ready(function() {
var picPicker, source;
function generateImage() {
$("img").fadeOut(2000, function() {
picPicker = (Math.floor(Math.random() * 200));
source = 'https://unsplash.it/400/300/?image=' + picPicker;
$("img").attr("src", source);
$("img").fadeIn(2000);
});
setTimeout(generateImage, 5000);
}
generateImage();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="https://unsplash.it/400/300/?image=1">

Does alert('some message') can make an impact in a callback function - Javascript

I had written a callback function to capture the snapshot of running video using html5 video control and canvas.
I used a for loop to iterate and call the same callback function take the burst capture. If i add alert('') in the callback , the video in the background rerendering when alert message display, the burst snap shot works fine as taking diff photos(frames/images of the running video). But when I removed the alert('') , the video does not run in the background and the bursted images are the same instead of different.
The code
for (var i = 0; i < burstcount; i++) {
var wcam = Webcam;
wcam.burst_snap(function (dataurl, id) {
var arrayindex = passedName + "_" + id;
imgid = imgid + i;
alert(dataurl);
burstcapturedata[arrayindex] = dataurl;
}, i);
var j = 0;
while (j < 10000000000) {
j++;
}
}
DisplayBurstedImages();
}
Yes, actually. Alert holds next execution of code. If your code works with alert it means that you require delay.
Try setTimeout or put the code in the correct place where everything is getting loaded.
I guess it needs time for binding video. you can use setTimeout function for delay.
var delay =100;
setTimeout(function () {/*your function*/ }, delay);
delay = delay + 300;
Your code needs to look something like this:
var wcam = Webcam;
var cnt = 0;
wcam.burst_snap(function(dataurl, id) {
var arrayindex = passedName + "_" + id; //you do not have an array if this is the key
imgid = imgid + cnt; //no clue what this is for
cnt++;
burstcapturedata[arrayindex] = dataurl;
if (cnt===burstcount) {
DisplayBurstedImages();
}
}, 100); //no clue what that value is supposed to be

How do I get my images to fade-in in a gallery using pure JavaScript?

My images are changing but the fade-in effect is not being applied. How do I get it to work? Should I be setting the opacity outside the changeImage() function?
JavaScript beginner here.
SCRIPT:
var imageArray = ["IMG1.jpg","IMG2.jpg",
"IMG3.jpg","IMG4.jpg"];
var imageIndex = 0;
var done = true;
var fading_image = document.getElementById("currentImg");
//To fade image
function function_opacity(opacity_value, fade_in_or_fade_out){
fading_image.style.opacity = opacity_value / 100;
fading_image.style.filter = 'alpha(opacity=' + opacity_value + ')';
if (fade_in_or_fade_out == 'in' && opacity_value == 1) {
fading_image.style.display = 'block';
}
if (fade_in_or_fade_out == 'in' && opacity_value == 100) {
done = true;
}
}
//To change image
function changeImage(){
document.getElementById("currentImg").src = imageArray[imageIndex];
imageIndex++;
if(imageIndex >= imageArray.length){
imageIndex = 0;
}
//Setting opacity
if (done && fading_image.style.opacity != '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout("function_opacity(" + i + ",'in')", i * 5);
}
}
};
setInterval(changeImage, 2000);
HTML
<img src="IMG1.jpg" id="currentImg" alt="Gallery Image">
There are a few reasons this issue may be occurring.
1) You probably need to use an anonymous function with setTimeout that contains the call to function_opacity, as the function takes parameters. setTimeout is expecting a function declaration, not an invocation.
2) Your i value may not be what you think it is. i contains a pointer to a value, not the value itself, and by the time the setTimeout is executed, your for loop has completed. This means that i would be 100 by the time function_opacity is called, making it look like your transition is not working.
Try changing the following code in changeImage and let me know how it goes.
//Setting opacity
if (done && fading_image.style.opacity != '1') {
done = false;
for (var i = 1; i <= 100; i++) {
setTimeout(function(){
function_opacity(this, "in");
}.bind(i), i*5);
}
}
I see a problem with your setTimeout implementation. The first argument to setTimeout must be a function reference, as opposed to a function invocation. You are using this concept properly in your setInterval. The visible difference is that you have no '()' after changeImage.
This raises another issue you will need resolved as you are passing arguments to your function_opacity invocation within the setTimeout. Try wrapping your function_opacity function invocation in an anonymous function

Change Attribute Every Second

I want an image to change every second. I'm having trouble with setInterval. Could someone post a quick snippet on how to do this
This is what I came up with.
var images = 'images/image_*.png';
for(var i = 1; i <= 5; i++){
function changeImg(){
var path = images.replace('*', i);
$('img').attr('src', path);
}
setInterval('changeImg()', 1000);
}
In your code you are calling the setInterval function 5 times which really is not necessary. Also as the loop will execute once, the value of i will always be 5 so it won't work as you expect. You may try this instead:
var images = 'images/image_*.png';
var i = 1;
setInterval(function() {
var path = images.replace('*', i);
$('img').attr('src', path);
i = i + 1;
if (i == 6) i = 1;
}, 1000);
Your loop was still continuing without waiting. Try writing it this way:
var images = 'images/image_*.png',
i = 1;
function changeImg(){
var path = images.replace('*', i);
$('img').attr('src', path);
i = (i == 5 ? 0 : i + 1);
}
window.setInterval(changeImg, 1000);
var images = 'images/image_*.png';
var i = 1;
function changeImg(i){
var path = images.replace('*', i);
$('img').attr('src', path);
}
setInterval('changeImg('+ ( (i++)%6 ) +')', 1000);
Maybe something like this ? I didn't test it though.

Categories

Resources