Continuously fade in and out random pictures - javascript

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">

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.

Change random result to sequence

How to change this random result into a sequence starting from lower number? I am new in JS and have tried to make modification with no solution. I hope anybody can help.
function randomFeed() {
var $el = $("#randomFeed");
var random = new Array('news1','news2','news3','news4','news5','news6');
var randomIndex = Math.floor(Math.random() * 4);
var newElement = random[randomIndex];
$el.prepend("<tr><td>" + newElement + "</td></tr>").find("tr").first().hide();
$el.find("tr").first().fadeIn();
if ($el.find("tbody tr").length > 20) {
$el.find("tbody tr").last().fadeOut(400, function() {
$(this).remove();
});
}
slimScrollUpdate($el.parents(".scrollable"));
setTimeout(function() {
randomFeed();
}, 3000);
}
So you need sequential news slide instead of random? Try this (note the global feedIndex variable)
var feedIndex = 0;
function randomFeed() {
var $el = $("#randomFeed"),
news = new Array('news1','news2','news3','news4','news5','news6'),
newElement = news[feedIndex++ % news.length];
//console.log(newElement);
$el.prepend("<tr><td>" + newElement + "</td></tr>").find("tr").first().hide();
$el.find("tr").first().fadeIn();
if ($el.find("tbody tr").length > 20) {
$el.find("tbody tr").last().fadeOut(400, function() {
$(this).remove();
});
}
slimScrollUpdate($el.parents(".scrollable"));
setTimeout(function() {
randomFeed();
}, 3000);
}
BTW, this code in it's state is very bad. It changes the DOM every time to show new feed element. It is better to render all elements whith display:none and only toggle visibility of actual one. It is common pattern
Try this:
news = new Array('news1','news2','news3','news4','news5','news6')
// option 1
news.sort(function() {
return .5 - Math.random();
});
//news = news1,news2,news3,news6,news4,news5
//option 2
len = news.length,
randomNumber = Math.floor((Math.random() * len) + 0);
// randomNumber = 3
part = news.slice(randomNumber, len)
// part = arrnews6,news4,news5
Please be more precise what are you expecting/about what your goal is!

Is there an universal solution for looping through and animating series of .png frames with jQuery / JavaScript?

I want to display a few animated "illustrations" on a website I'm working on.
.gif is not an option due to significant loss of quality.
Is there any solution out there that would allow me to iterate through a folder of PNG's and display them on screen?
Thanks in advance.
something like this will work if the images are named 1.png through 25.png for example.
var slides = 25; //number of slides
var i = 1; //first slide
var delay = 200; //set delay
var timer;
function pngani() {
if (i <= slides) {
$('#show img').attr('src', 'pathtofile/' + i + '.png');
}
i++;
}
$('#start').click(function () {
timer = setInterval(pngani, delay);
pngani();
});
$('#pause').click(function () {
clearInterval(timer);
timer = null;
});
$('#reset').click(function () {
i = 1;
$('#show img').attr('src', 'pathtofile/' + i + '.png');
});
I added a start, pause, and reset button, so the execution can be controlled.
made a fiddle: http://jsfiddle.net/filever10/Kur9u/

Proper deleting HTML DOM nodes

I'm trying to create a star shining animation.
function ShowStars()
{
//if ($('img.star').length > 5)
// return;
var x = Math.floor(Math.random() * gameAreaWidth) - 70;
var y = Math.floor(Math.random() * gameAreaHeight);
var star = document.createElement("img");
star.setAttribute("class", "star");
star.setAttribute("src", imagesPath + "star" + GetRandom(1, 3) + ".png");
star.style.left = x + "px";
star.style.top = y + "px";
gameArea.appendChild(star);
// Light.
setTimeout(function () { star.setAttribute("class", "star shown"); }, 0);
// Put out.
setTimeout(function () { star.setAttribute("class", "star"); }, 2000);
// Delete.
setTimeout(function () { gameArea.removeChild(star); }, 4000);
setTimeout(function () { ShowStars(); }, 500);
}
It works fine until I uncomment the following code which is supposed to regulate star count:
//if ($('img.star').length > 5)
// return;
Then it stops to work as if the created stars are not removed (the first 5 stars blink then nothing happens). Why do the jQuery selector select them after gameArea.removeChild(star);? Isn't it enough to remove them from the parent node?
Browser: Google Chrome 17.
Regards,
Change the commented out lines to
if ($('img.star').length > 5) {
setTimeout(function () { ShowStars(); }, 500);
return;
}
to keep the ShowStars recursion going.
I see a workaround: do not create stars dynamically, but insert them in HTML (<img id="star1">...<img id="starN">, where N is total count) then light and put out the existing nodes. Nevertheless, I'd like to understand, what's wrong with removing nodes in the question above.

Setting a time for flicker animation on img

I'm using this code to make my logo flicker on my website. But It becomes annoying when it continues to flicker while browsing, how can I set a time to allow it to flicker for something like the first 15seconds on page load, then stops?
JS code I'm using:
$(document).ready(
function(){
var t;
const fparam = 100;
const uparam = 100;
window.flickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","hidden");
t = setTimeout('window.unflickr()',uparam);
}
else
t = setTimeout('window.flickr()',fparam);
}
window.unflickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","visible");
t = setTimeout('window.flickr()',fparam);
}
else
t = setTimeout('window.unflickr()',uparam);
}
t = setTimeout('window.flickr()',fparam);
});
You could have a counter, which you then use to decide whether you want to set another timeout. As a side note, you should never add functions to window and then passing a string to setTimeout. Always just pass the function itself:
$(document).ready(function(){
var t;
var amount = 0;
const fparam = 100;
const uparam = 100;
function timeout(f, t) { // this function delegates setTimeout
if(amount++ < 150) { // and checks the amount already (un)flickered
setTimeout(f, t); // (150 * 100 ms = 15 s)
}
}
var flickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","hidden");
t = timeout(unflickr,uparam);
}
else
t = timeout(flickr,fparam);
};
var unflickr = function(){
if(Math.round(Math.random())){
$("#logodcoi").css("visibility","visible");
t = timeout(flickr,fparam);
}
else
t = timeout(unflickr,uparam);
};
t = timeout(flickr,fparam);
});
I see you're using jquery, you could use the following, if I remember correctly, all the stuff I use below has been in jquery since 1.0, so you should be good:
counter = 1;
function hideOrShow(){
$(".classToSelect").animate({"opacity": "toggle"}, 100);
counter = counter +1;
if (counter >= 21) clearInterval(flickerInterval);
}
flickerInterval = setInterval(hideOrShow, 100);
Change the selector, animation duration, and variable names to whatever you fancy/need.

Categories

Resources