Replace background image given an array of images - javascript

I am trying to set a background image rotation for a div with a image already in it, doesn't seem to change anything, thought I would check if someone could see the problem since no errors come up.
<script>
$( document ).ready(function() {
setInterval(function() {
var tips = [
"header.jpg",
"header2.jpg",
"header3.jpg",
"header4.jpg",
"header5.jpg",
];
var i = 0;
if (i == tips.length) --i;
$('.containercoloring').fadeTo('slow', 0.3, function()
{
$(this).css('background-image', 'url(' + tips[i] + ')');
}).delay(1000).fadeTo('slow', 1);
i++;
}, 5 * 1000);
});
</script>
<body>
<div class="containercoloring"> </div>
</body>

Below is the working(updated) code. I hope you are importing jquery lib separately.
<script>
$(document).ready(function() {
var i = 0;
setInterval(function() {
var tips = [
"header.jpg",
"header2.jpg",
"header3.jpg",
"header4.jpg",
"header5.jpg"
];
var imageIndex = ++i % tips.length;
$('.containercoloring').fadeTo('slow', 0.3, function() {
$(this).css('background-image', 'url(' + tips[imageIndex] + ')');
}).delay(1000).fadeTo('slow', 1);
}, 5 * 1000);
});
</script>
<body>
<div class="containercoloring" style="height: 100px;">Image Container</div>
</body>
You can test here in this jsfiddle - https://jsfiddle.net/nbq9f6bg/
Hope it helps!

So there were a couple of notes I had about your example. Please see the comments below. I used background color and removed the transitions to show it easier.
// declare variables
var tips = [
"#ff9000",
"#ff0000",
"#0099ff"
];
// counter
var i = 0;
// direction
var direction = 'forwards';
// time in between intervals
var timer = 2000;
function changeBackground() {
// Check the length minus 1 since your counter starts at 0
if (i == (tips.length - 1)) {
direction = 'backwards';
} else if(i == 0) {
// only set the direction back to forwards when the counter is 0 again
direction = 'forwards';
}
$('.containercoloring').css('background-color', tips[i]);
// add or subtract based on the direction
if(direction == 'forwards') {
i++;
} else {
i--;
}
}
$( document ).ready(function() {
// save interval to a variable so you can stop it later
var theInterval = setInterval(changeBackground, timer);
// run the function since the interval will take 2000ms to execute
changeBackground();
});
.containercoloring {
height: 100px;
width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="containercoloring"> </div>

Related

Javascript div fade in not working using setInterval

I'm trying to make a div containing a number of pictures to fade in but its not working and I don't know why. I believe that the inverval is not even being called. The div's opacity is set to 0.0 This is the code:
var movies = getElementById("movies");
var apparence = function(){
if(movies.style.opacity < 1.0){
movies.style.opacity = movies.style.opacity + 0.1;
} else { clearInterval(timer);
}
}
var timer = window.setInterval(apparence, 1000);
Thank you very much.
To set your movies var, you need to call:
document.getElementById('movies');
The way you are attempting to increment opacity didn't work, so I've updated your example.
New Code:
var movies = document.getElementById("movies");
var opacity = 0.1;
var apparence = function(){
if(opacity <= 1.0) {
movies.style.opacity = opacity;
} else {
clearInterval(timer);
}
opacity += 0.1;
}
var timer = window.setInterval(apparence, 1000);
JS Fiddle:
http://jsfiddle.net/onov6cq4/1/
Here is your problem
Problem1:
If you have defined your css using
#movies {
opacity: 0.0;
}
then document.getElementById().style.opacity is empty since it takes from inline style i.e. <div id="movies" style="opacity: 0.0">
Problem 2:
movies.style.opacity = movies.style.opacity + 0.1;
movies.style.opacity returns a string so you are basically appending string which results in 0.10.1 and so on. You need to do parseFloat! The attached fiddle will solve your problem
Code:
var moviesOp = document.getElementById('movies').style.opacity;
function apparence(){
console.log('interval called with op = ' + moviesOp);
if(moviesOp < 1.0){
moviesOp = parseFloat(moviesOp, 10) + 0.1;
} else {
clearInterval(timer);
}
}
var timer = setInterval(apparence, 1000);
<div id="movies" style="opacity: 0.0">
JSBin With Inline Style
If you want to use in css and not inline then use getComputedStyle. This i tried and works as u wanted
var movies = document.getElementById('movies');
function apparence(){
var moviesOp = getComputedStyle(movies).getPropertyValue('opacity');
console.log('interval called with op = ' + moviesOp);
if(moviesOp < 1.0){
movies.style.opacity = parseFloat(moviesOp, 10) + 0.1;
} else {
clearInterval(timer);
}
}
var timer = setInterval(apparence, 1000);
Non Inline jsBin

How to animate the HTML contents using jquery..

I have an HTMl texts that is getting changed dynamically.Now as per my requirement i have to display them in animated form like fading and in some motion but i am not aware of this ..
Here is my Code..
<script type="text/javascript">
var v = {};
v[0] = "Your Text<br/>Hello";
v[1] = "Your Text2<br/>Hello2";
v[2] = "Your Text3<br/>Hello3";
var i = 0;
window.setInterval(function () {
$("#dynamicMessage").html(v[i]);
if (i == 2) {
i = 0;
} else {
i = i + 1;
}
}, 10000);
</script>
Please have a look and let me know how can i animate my text contents in HTML..
Thanks..
You could use a combination of fadeOut() and fadeIn()
$("#dynamicMessage").fadeOut( "slow", function() {
$("#dynamicMessage").html(v[i]).fadeIn('slow');
})
Check this demo - http://jsfiddle.net/xw2j6hsp/1/
UPDATE
Saw this comment, on #laruiss answer:
"If there are other way by which i can show the text popping from the
left"
Thought i'd code this up for you. Just add in some animation. check it - http://jsfiddle.net/m6bnq1ja/
There's no animating the content change. What you can do is hide the element, change its content, then fade it in, something like below. It'll probably look the same to the user.
$("#dynamicMessage").hide().html(v[i]).fadeIn();
or
$("#dynamicMessage").fadeOut(500, function() {
$(this).html(v[i]).fadeIn(500);
});
Don't forget to clearTimeout (or clearInterval)
var v = [
"Your Text<br/>Hello",
"Your Text2<br/>Hello2",
"Your Text3<br/>Hello3"
],
i = 0,
timeout = null,
change = function (text) {
var $dynamicMessage = $("#dynamicMessage")
.fadeOut("slow", function() {
$dynamicMessage.html(text).fadeIn();
});
if (i == 2) {
i = 0;
} else {
i = i + 1;
}
timeout = window.setTimeout(function() {change(v[i]);}, 2000);
}
change(v[i]);
$(window).unload(function() {window.clearTimeout(timeout); timeout = null;});
JSFiddle
var v = {};
v[0] = "Your Text<br/>Hello";
v[1] = "Your Text2<br/>Hello2";
v[2] = "Your Text3<br/>Hello3";
var i = 0;
window.setInterval(function () {
$("#dynamicMessage").fadeToggle( "slow", function() {
$("#dynamicMessage").html(v[i]).fadeToggle('slow');
});
if (i == 2) {
i = 0;
} else {
i = i + 1;
}
}, 4000);
Note : you can also use "fadeOut" & "fadeIn" in place of "fadeToggle"

I want to create image gallery with infinite loop using jquery

I want to create an image gallery, I wrote for a slideshow, but I don't know how to code for the previous and next buttons. These should work like an infinite loop (last image jumps back to the first).
How should I get started? This is what I have so far:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#play").click(function () {
$("#img1").fadeOut(2000);
$("#img2").fadeIn();
$("#img2").fadeOut(4000);
$("#img3").fadeIn();
});
});
</script>
<body>
<div id=outer>
<div id=inner>
<img id="img1" src="img1.jpg"/>
<img id="img2" src="img2.jpg" style="display:none"/>
<img id="img3" src="img3.jpg" style="display:none"/>
</div>
<div id=button>
<button id="bwd"><<</button>
<button id="play"><></button>
<button id="fwd">>></button>
</div>
</div>
</body>
You can use setInterval() .
This link can help you to understand much more
Call function with setInterval in jQuery?
may be this can help you too :
http://jquery.malsup.com/cycle/
you're going to want to use the javascript timing function. Something like:
$('#play').click(function(){
window.setInterval(function(){
if($('#img1').is(:visible)){
$("#img2").show()
$("#img1").hide()
}
if($('#img2').is(:visible)){
$('#img3').show()
$('#img2').hide()
}
if($('#img3').is(:visible)){
$('#img1').show()
$('#img3').hide()
}
}, 1000);
});
You can also condense this logic down, but this gets you the basic idea. Then if you look carefully the functions for next is already in the code and it can be extracted out and reuses. Once you have the next function it's pretty straight forward that the back function will be the exact opposite.
To answer your question below you can change the img's to have the same class and then apply show and hide based on which one is visible and the image immediately after the visible one:
#find the one currently being shown
$(".images:visible")
#find the one after the visible one
$(".images:visible").next()
#keep an id on the last image so that you can do something like
if($('.images:visible') == $('#last_image')){
$('.images').first().show()
}
Hi i have created Carousel without using any third party plugin.If you want please refer.Reference Link
Js Code is.
$(document).ready(function () {
var currentPosition = 0;
var slideWidth = 300;
var slides = $('.slide');
var numberOfSlides = slides.length;
var timer = 3000;
var img1, img2;
var sliderLink = $("#slider a");
var direction = 1;
// Remove scrollbar in JS
$('#slidesContainer').css('overflow', 'hidden');
// Wrap all .slides with #slideInner // Float left to display horizontally, readjust .slides width
slides.wrapAll('<div id="slideInner"></div>').css({
'float': 'left',
'width': slideWidth
});
// Set #slideInner width equal to total width of all slides
$('#slideInner').css('width', slideWidth * numberOfSlides);
// Insert left and right arrow controls in the DOM
$('#slideshow').prepend('<span class="control" id="leftControl">Move left</span>').append('<span class="control" id="rightControl">Move right</span>');
// Hide left arrow control on first load
// manageControls(currentPosition);
// manageSlide();
// Create event listeners for .controls clicks
$('#rightControl').bind('click', rightControl);
$('#leftControl').bind('click', leftControl);
function leftControl() {
var butonid = 0;
direction = 0;
$("#slideInner").stop();
$("#slideInner").dequeue();
$('#timer').stop();
$('#timer').dequeue();
$('#leftControl').unbind('click');
manageSlide(0, direction);
setTimeout(function () {
$('#leftControl').bind('click', leftControl);
}, timer, null);
}
function rightControl() {
var butonid = 1;
direction = 1;
$("#slideInner").stop();
$("#slideInner").dequeue();
$('#timer').stop();
$('#timer').dequeue();
$('#rightControl').unbind('click');
manageSlide(0, direction);
setTimeout(function () {
$('#rightControl').bind('click', rightControl);
}, timer, null);
}
var slideIndex = 0;
var data = $("#slideInner .slide").toArray();
$("#slideInner").empty();
function manageSlide(auto, idButtonid) {
$("#slideInner").empty();
// console.log(slideIndex);
if (idButtonid == 0) {
$("#slideInner").css({ 'marginLeft': "-300px" });
$(data).each(function (index) {
// if (index == slideIndex - 1) {
// $(this).show();
// } else {
$(this).hide();
// }
});
$(data[slideIndex - 1]).show();
if (slideIndex == numberOfSlides - 1) {
slideIndex = 0;
img1 = data[0];
img2 = data[numberOfSlides - 1];
$("#slideInner").append(img1);
$("#slideInner").append(img2);
$(img2).show();
$(img1).show();
} else {
img1 = data[slideIndex];
img2 = data[slideIndex + 1];
$("#slideInner").append(img2);
$("#slideInner").append(img1);
$(img1).show();
$(img2).show();
slideIndex = slideIndex + 1;
}
$('#slideInner').animate({
'marginLeft': "0px"
}, 'slow', function () {
$('#timer').animate({
opacity: 1
}, timer, function () {
console.log('leftControl');
manageSlide(1, direction);
});
});
}
// right move here
else if (idButtonid == 1) {
$("#slideInner").css({ 'marginLeft': "0px" });
$(data).each(function (index) {
if (index == slideIndex + 1) {
$(this).show();
} else {
$(this).hide();
}
});
if (slideIndex == numberOfSlides - 1) {
slideIndex = 0;
img1 = data[0];
img2 = data[numberOfSlides - 1];
$("#slideInner").append(img2);
$("#slideInner").append(img1);
$(img2).show();
$(img1).show();
} else {
img1 = data[slideIndex];
img2 = data[slideIndex + 1];
$("#slideInner").append(img1);
$("#slideInner").append(img2);
$(img1).show();
$(img2).show();
slideIndex = slideIndex + 1;
}
$('#slideInner').animate({
'marginLeft': slideWidth * (-1)
}, 'slow', function () {
console.log('rightControl');
$('#timer').animate({
opacity: 1
}, timer, function () {
manageSlide(1, direction);
});
});
}
if (auto == 1) {
sliderLink.each(function () {
$(this).removeClass();
if ($(this).text() == (slideIndex + 1)) {
$(this).addClass('active');
}
});
}
auto = 1;
}
$("#slider a").click(function () {
sliderLink.each(function () {
$(this).removeClass();
});
slideIndex = $(this).addClass('active').text() - 1;
$('#timer').stop();
$('#timer').dequeue();
$("#slideInner").stop();
$("#slideInner").dequeue();
manageSlide(0, direction);
});
manageSlide(1, direction);
});
Demo Link
Hope it helps you.

Display diffrent image depending on timer

I'm trying to display a different image depending on the timer's result and can't find a way through. So far I have a start and stop button, but when I click stop, I want to use the value the timer is on and display an image(on alertbox or the webpage itself) depending on that value.
if( timer =>60){
img.src("pizzaburnt.jpg");
}elseif (timer <=30){
img.src("pizzaraw.jpg");
}
else{
img.src("pizzaperfect.jpg
}
///Time
var check = null;
function printDuration() {
if (check == null) {
var cnt = 0;
check = setInterval(function () {
cnt += 1;
document.getElementById("para").innerHTML = cnt;
}, 1000);
}
}
//Time stop
function stop() {
clearInterval(check);
check = null;
document.getElementById("para").innerHTML = '0';
}
**HTML**
<td>
Timer :<p id="para">0</p>
</td>
Any advice or dicussion would be great, thanks.
Something like this would work better and it's more compact:
var img = document.getElementById("image");
var imageSrcs = ['pizzaRaw.jpg', 'pizzaPerfect.jpg', 'pizzaBurnt.jpg'];
var imageIndex = 0;
var interval = setInterval(animate, 30000); //change image every 30s
var animate = function() {
//change image here
//using jQuery:
img.src(imageSrcs[imageIndex]);
imageIndex++; //move index for next image
if (imageIndex == imageSrcs.length) {
clearInterval(interval); //stop the animation, the pizza is burnt
}
}
animate();
Reason you wouldn't want to use an increment variable and a 1 second timer is because your just conflating your logic, spinning a timer, and making a bit of a mess when all you really want is the image to change every 30 seconds or whenever.
Hope this helps.
You need an <img> tag in your HTML like this:
<html>
<body>
Timer: <p id="para">0</p>
Image: <img id="image" />
</body>
</html>
And the Javascript code will be like:
var handle;
var timerValue = 0;
var img = document.getElementById( "image" );
var para = document.getElementById("para");
function onTimer() {
timerValue++;
para.innerHTML = timerValue;
if ( timerValue >= 60 ) {
img.src( "pizzaburnt.jpg" );
}else if ( timer <= 30 ) {
img.src( "pizzaraw.jpg" );
} else {
img.src("pizzaperfect.jpg" );
}
}
function start () {
if ( handle ) {
stop();
}
timerValue = 0;
setInterval( onTimer, 1000 );
}
function stop () {
if ( handle ) {
clearInterval ( handle );
}
}
Please make sure that these 3 files are in the same directory as your HTML file:
pizzaburnt.jpg
pizzaraw.jpg
pizzaperfect.jpg

Can you count clicks on a certain frame in an animation in javascript?

I'm looking to build a very simple whack a mole-esque game in javascript. Right now I know how to do everything else except the scoring. My current animation code is as follows
<script language="JavaScript"
type="text/javascript">
var urls;
function animate(pos) {
pos %= urls.length;
document.images["animation"].src=urls[pos];
window.setTimeout("animate(" + (pos + 1) + ");",
500);
}
window.onload = function() {
urls = new Array(
"Frame1.jpg","Frame2.jpg"
);
animate(0);
}
</script>
So far it all works, the first frame is the hole and the second is the groundhog/mole out of the hole. I need to count the clicks on the second frame but I can't figure out how to incorporate a counter. Help? (Sorry if the code doesn't show up correctly, first time using this site)
Here is an example that counts clicks on the flashing animation: http://jsfiddle.net/maniator/TQqJ8/
JS:
function animate(pos) {
pos %= urls.length;
var animation = document.getElementById('animation');
var counter = document.getElementById('counter');
animation.src = urls[pos];
animation.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
setTimeout(function() {
animate(++pos);
}, 500);
}
UPDATE:
Here is a fiddle that only detects click on one of the images: http://jsfiddle.net/maniator/TQqJ8/8/

Categories