Javascript two interval image change - javascript

I have an image that I want to stay on screen for 5 seconds and then change to another image for .5 of a second and then change back to the original.
I've set the interval to change every 5 seconds but I can't seem to work out how to make it change for the according times.
Any help or direction would be greatly appeciated!
window.setInterval(function() {
var img = document.getElementById("glitch");
img.src = "2-01.svg";
}, 5000);

Try this:
const images = ["1.svg", "2.svg"]
var element = document.getElementById("glitch");
function showFirst() {
setTimeout(() => {
element.src = images[0];
showSecond()
}, 5000)
}
function showSecond() {
setTimeout(() => {
element.src = images[1];
showFirst()
}, 500)
}
showFirst()

You are always changing the image src to same "2-01.svg" every time. Please use some flag/condition to alternate the image src.
Here is what you can try ::
window.setInterval(function() {
var img = document.getElementById("glitch");
if(img.src == "2-01.svg") {
img.src = "2-00.svg"
}
else {
img.src = "2-01.svg";
}
}, 5000);

I was doing some test watching the thread.
If that can help you (this is not a clean code) :
img_to_change = document.querySelector("#glitch");
imgs = {"a":10, "b":2, "c":3}
keys = Object.keys(imgs)
run = function(i){
img_src = keys[i];
img_next_time = imgs[keys[i]];
img_to_change.src = img_src;
i = (i+1) == keys.length ? -1 : i;
setTimeout(() => {
img_to_change.src = img_src;
run(i+1);
}, img_next_time*1000)
}
run(0);
http://jsfiddle.net/pn3dyb5m/32/

Related

How to flash background image on square after document.querySelectorAll('.square')

I am working on a whac a mole game where the background image should flash when the square is hit. For example an image that says "hit".
The square has been targeted correctly on function showImage(), tested with a console.log, and called in a forEach loop. I don't know the next step. I know I need to grab css class with background image of square and add an image. Maybe a set timer is involved. I have tried this and cannot get it working. See codepen
const squares = document.querySelectorAll('.square')
const mole = document.querySelector('.mole')
const timeLeft = document.querySelector('#time-left')
const score = document.querySelector('#score')
let result = 0
let hitPosition
let currentTime = 60
let timerId = null
function showImage() {
if ((document.onclick = squares)) {
squares.style.backgroundColor = 'green';
//console.log('it is working');
} else {
alert('it is not working');
}
}
function randomSquare() {
squares.forEach(square => {
square.classList.remove('mole')
})
let randomSquare = squares[Math.floor(Math.random() * 9)]
randomSquare.classList.add('mole')
hitPosition = randomSquare.id
}
squares.forEach(square => {
square.addEventListener('mousedown', () => {
if (square.id == hitPosition) {
result++
score.textContent = result
hitPosition = null
showImage();
}
})
})
function moveMole() {
timerId = setInterval(randomSquare, 500)
}
moveMole()
function countDown() {
currentTime--
timeLeft.textContent = currentTime
if (currentTime == 0) {
clearInterval(countDownTimerId)
clearInterval(timerId)
alert('GAME OVER! Your final score is ' + result)
}
}
let countDownTimerId = setInterval(countDown, 1000)
Sounds like this could handled by a class that displays an image in the background.
.bg-img {
background-image: url('');
}
And then in the function showImage() you set the class name bg-img on the element:
function showImage() {
squares.classList.add('bg-img');
setTimeout(function(){
squares.classList.remove('bg-img');
}, 1000);
}
And remove the class name again 1000 ms after.

Change Picture in CSS Style Dynamically

I have style id like this
#Myimage {
width: 797px;
height: 317px;
background:url(images/templatemo_header_pizza.jpg) no-repeat;
And I want to change the picture every 5 sec.
I am new to JavaScript and jQuery but the main idea something like this
function ()
{
ImageArray = LoadImage("Baseimage/*.jpg")
while(true)
{
For(i in ImageArray)
{
Myimage.background:url = i;
waitfor(5);
}
}
}
var imgArray = ["image1.jpg","image2.jpg"];
var counter = 0;
function changeImages() {
counter++;
$("#MyImage").css("background-image",'url(' +imgArray[counter] + ')')
if(counter == 1) {
counter = -1;
}
}
setInterval(changeImages,5000)
Attach a Jquery lib. and past that JQuery script in you head section:
$(window).load(function() {
var i =0;
var images = ['image2.png','image3.png','image1.png'];
var image = $('#Myimage');
//Initial Background image setup
image.css('background-image', 'url(image1.png)');
//Change image at regular intervals
setInterval(function(){
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + images [i++] +')');
image.fadeIn(1000);
});
if(i == images.length)
i = 0;
}, 5000);
});
You can use Image to check if the image exists:
$(function () {
var base = "myImage_*.jpg", img, c = 0, ar = [], o = 0;
function recurse () {
img = new Image();
img.src = base.replace('*', ++c);
img.onload = function () {
ar.push(img.src);
recurse();
}
img.onerror = function () {
c = -1;
function r() {
$("yourElement").css("background-image", "url("+ar[c++ >= ar.length ? (c=0) : c]+")");
setTimeout(r, 2000); // 2000 is two seconds
}
}
}
});

Applying transitions to preloaded images

I'm using the jQuery plugin Images-rotation in order to create a slideshow that plays when hovering over an image. I'd like to add transitions between the images, such as jQuery's fadeIn. The images are preloaded, which is why I think what I've attempted so far hasn't been successful.
I've also created this (http://jsfiddle.net/Lydmn2xn/) to hopefully easily show what's being used, although all of the code is found in the Javascript plugin itself. So far I've tried adding variations of the line $this.fadeIn("slow"); in various spots with no luck. Below is the code for the Javascript plugin with changes I've tried to make. Not sure how to point them out as I can't bold the text in the code. (Note: said changes are not in the Jfiddle, as they don't produce any changes).
$.fn.imagesRotation = function (options) {
var defaults = {
images: [], // urls to images
dataAttr: 'images', // html5 data- attribute which contains an array with urls to images
imgSelector: 'img', // element to change
interval: 1500, // ms
intervalFirst: 1500, // first image change, ms
callback: null // first argument would be the current image url
},
settings = $.extend({}, defaults, options);
var clearRotationInterval = function ($el) {
clearInterval($el.data('imagesRotaionTimeout'));
$el.removeData('imagesRotaionTimeout');
clearInterval($el.data('imagesRotaionInterval'));
$el.removeData('imagesRotaionInterval');
},
getImagesArray = function ($this) {
var images = settings.images.length ? settings.images : $this.data(settings.dataAttr);
return $.isArray(images) ? images : false;
},
preload = function (arr) { // images preloader
$(arr).each(function () {
$('<img/>')[0].src = this;
$this.fadeIn("slow");
});
},
init = function () {
var imagesToPreload = [];
this.each(function () { // preload next image
var images = getImagesArray($(this));
if (images && images.length > 1) {
imagesToPreload.push(images[1]);
}
});
preload(imagesToPreload);
};
init.call(this);
this.on('mouseenter.imagesRotation', function () {
var $this = $(this),
$img = settings.imgSelector ? $(settings.imgSelector, $this) : null,
images = getImagesArray($this),
imagesLength = images ? images.length : null,
changeImg = function () {
var prevIndex = $this.data('imagesRotationIndex') || 0,
index = (prevIndex + 1 < imagesLength) ? prevIndex + 1 : 0,
nextIndex = (index + 1 < imagesLength) ? index + 1 : 0;
$this.data('imagesRotationIndex', index);
if ($img && $img.length > 0) {
if ($img.is('img')) {
$img.attr('src', images[index]);
$this.fadeIn('slow');
}
else {
$img.css('background-image', 'url(' + images[index] + ')');
$img.fadeIn('slow');
}
}
if (settings.callback) {
settings.callback(images[index]);
}
preload([images[nextIndex]]); // preload next image
};
if (imagesLength) {
clearRotationInterval($this); // in case of dummy intervals
var timeout = setTimeout(function () {
changeImg();
var interval = setInterval(changeImg, settings.interval);
$this.data('imagesRotaionInterval', interval); // store to clear interval on mouseleave
}, settings.intervalFirst);
$this.data('imagesRotaionTimeout', timeout);
}
}).on('mouseleave.imagesRotation', function () {
clearRotationInterval($(this));
}).on('imagesRotationRemove', function () {
var $this = $(this);
$this.off('.imagesRotation');
clearRotationInterval($this);
});
};
$.fn.imagesRotationRemove = function () {
this.trigger('imagesRotationRemove');
};
Would that do the trick if it was in the right spot, or does fadeIn/Out not apply to preloaded images? Any help or tips are appreciated.
Thanks.

Preloading images - not working on floated images

I have an image preloading script which is slightly modified version of this one form nettuts : http://net.tutsplus.com/tutorials/javascript-ajax/how-to-create-an-awesome-image-preloader/
The problem I am having is that the preload background gif isnt working on images that are floated?
// JavaScript Document
$.fn.preloader = function(options){
var defaults = {
delay:20000,
preload_parent:"span",
check_timer:300,
ondone:function(){ },
oneachload:function(image){ },
fadein:500
};
// variables declaration and precaching images and parent container
var options = $.extend(defaults, options),
root = $(this) , images = root.find("img").css({"visibility":"hidden",opacity:0}) , timer , counter = 0, i=0 , checkFlag = [] , delaySum = options.delay ,
init = function(){
timer = setInterval(function(){
if(counter>=checkFlag.length)
{
clearInterval(timer);
options.ondone();
return;
}
for(i=0;i<images.length;i++)
{
if(images[i].complete==true)
{
if(checkFlag[i]==false)
{
checkFlag[i] = true;
options.oneachload(images[i]);
counter++;
delaySum = delaySum + options.delay;
}
$(images[i]).css("visibility","visible").delay(delaySum).animate({opacity:1},options.fadein,
function(){ $(this).parent().removeClass("preloader"); });
}
}
},options.check_timer)
} ;
images.each(function(){
if($(this).parent(options.preload_parent).length==0)
$(this).wrap("<span class='preloader' />");
else
$(this).parent().addClass("preloader");
checkFlag[i++] = false;
});
images = $.makeArray(images);
var icon = jQuery("<img />",{
id : 'loadingicon' ,
src : 'css/i/89.gif'
}).hide().appendTo("body");
timer = setInterval(function(){
if(icon[0].complete==true)
{
clearInterval(timer);
init();
icon.remove();
return;
}
},100);
}
$(function () {
$("#righthalf").preloader();
$("#portright").preloader();
$("#timeline").preloader();
$("#type").preloader();
})
Any ideas guys?

JavaScript Sleep Function

I have a banner rotator that refreshes every 60 seconds however I would also like each banner to be displayed for 20 seconds as there are 3 of them. I know where to put the setInterval code as indicated by my comment but I can't seem to get it to work. Any help or suggestions are very much appreciated.
var banners1 = {
0:
{
'href': 'http://www.example.com/banner1.html',
'src': 'http://www.example.com/banner1.gif'
},
1:
{
'href': 'http://www.example.com/banner2.html',
'src': 'http://www.example.com/banner2.gif'
},
2:
{
'href': 'http://www.example.com/banner3.html',
'src': 'http://www.example.com/banner3.gif'
}
}
window.addEvent('domready', function() {
function banner1()
{
var banner = $('banner1');
var banner1Link = $('banner1').getElement('a');
var banner1Image = $('banner1').getElement('img');
for (var keys in banners1) {
var object = banners1[keys];
for (var property in object) {
if (property == 'href') {
var href = object[property];
}
if (property == 'src') {
var src = object[property];
}
}
banner1Link.setProperty('href', href);
banner1Image.setProperty('src', src);
console.log(href);
console.log(src);
/** wait 20 seconds **/
}
}
var periodical = banner1.periodical(60000);
});
Try this instead:
function banner1()
{
var banner = $('banner1');
var banner1Link = $('banner1').getElement('a');
var banner1Image = $('banner1').getElement('img');
var delay = 0;
for (var keys in banners1) {
var func = (function(key) { return function() {
var object = banners1[key];
for (var property in object) {
if (property == 'href') {
var href = object[property];
}
if (property == 'src') {
var src = object[property];
}
}
banner1Link.setProperty('href', href);
banner1Image.setProperty('src', src);
console.log(href);
console.log(src);
}; })(keys);
setTimeout(func, delay);
delay += 20000;
}
}
JavaScript does not have a sleep-style function, because the document will not respond while JavaScript is running. This means the user would not be able to interact with the page while the script is sleeping.
This approach schedules all three updates in one shot. They will execute at 0 seconds (immediately), 20 seconds, and 40 seconds from the time the script runs.
you could use the javascript timeout
setTimeout('', 20000);
This would be added right after the 20 sec comment. The first variable is any code/function you want called. and the second is the amount of time required before it is called in milliseconds (20 secs).
EDITED ANSWER
<script type="text/javascript">
var imgs1 = new Array("http://www.omniadiamond.com/images/jwplayer/enel_culture.png","http://www.omniadiamond.com/images/jwplayer/evas_srm.png","http://www.omniadiamond.com/images/jwplayer/jackolantern.png");
var lnks1 = new Array("http://test.com","http://test.com","http://test.com");
var alt1 = new Array("test","test","test");
var currentAd1 = 0;
var imgCt1 = 3;
function cycle1() {
if (currentAd1 == imgCt1) {
currentAd1 = 0;
}
var banner1 = document.getElementById('adBanner1');
var link1 = document.getElementById('adLink1');
banner1.src=imgs1[currentAd1]
banner1.alt=alt1[currentAd1]
document.getElementById('adLink1').href=lnks1[currentAd1]
currentAd1++;
}
window.setInterval("cycle1()",20000);
</script>
<a href="http://test.com" id="adLink1" target="_top">
<img src="http://www.omniadiamond.com/images/jwplayer/enel_culture.png" id="adBanner1" border="0"></a>
This does cycle through all three in 60 secs at a 20 sec interval. and can be viewed at http://jsfiddle.net/jawilliams346614/wAKGp/ (it is set to a 1 sec interval)

Categories