Need Jquery chaning My Background image in a DIV - javascript

I`m starting level in jquery , but i have the concept of my idea , i have a #SlidShow div , all i need to change the css property ( background-image ) every 3 second , i have i think 4 image , so my concept is (( Make New Array with images link )) and change the .css( background-image ) of this div with this array every 3s ..
i hope that my concept be right :) , can any one help me with that
#('SlideShow').css('background-image', (Array /* Cant handle it */));

var array = ['url(a.png)', 'url(b.png)', 'url(c.png)', 'url(d.png)'];
var i = 0;
function setBackgroundImage() {
$('#SlideShow').css('background-image', array[i]);
i = i % array.length;
}
setBackgroundImage();
setInterval(setBackgroundImage, 3000);

You already got your answer. Just wanted to add that jQuery is a bit overkill if this is all you want to do, but it's probably not.
Here is a pure javascript solution:
http://jsfiddle.net/2BQV5/2/
var arr = ['http://placekitten.com/200/300','http://placekitten.com/200/301','http://placekitten.com/200/302'];
window.onload = function ()
{
index = 0;
var c = document.getElementById('cat');
setInterval(function() {
if(index > arr.length-1) {index = 0}
c.style.backgroundImage='url(' + arr[index++] + ')';
}, 3000);
}
Have fun!
Edit
However for the second request in the comments, to have to pictures fade, jQuery is probably more suited.
Here is one way to achieve the fading effect:
http://jsfiddle.net/8jWT5/
var arr = ['http://placekitten.com/200/300','http://placekitten.com/200/301','http://placekitten.com/200/302'];
$(document).ready(function() {
var c = $('#cat');
fade = document.createElement('div');
$(fade).attr('style','position: absolute; width:' + c.width() + 'px; height:' + c.height() + 'px;').attr('id','fade').hide();
c.append(fade);
var index = 0;
setInterval(function () {
$('#fade').css('background-image', 'url(' + arr[index] + ')').fadeIn(500,function() {
c.css('background-image', 'url(' + arr[index++] + ')');
if(index > arr.length-1) {index = 0}
$(this).hide();
});
}, 3000);
});

Related

How we can move CSS object from Right to Left using javascript?

Hi, In javascript we have option of finding offSetRight position of Element and can move it towards Left to Right side using setInterval method but i like to bring that object from right to left and i did not find any javascript method which i can use Here in my code , if you guys can take a look it would be great, also i like to mention i am new to Js so i hope people will go easy on me.
P.s - CSS and Jquery not allowed for animation.
var e = document.getElementById("aDiv");
var s = 1;
function myInterval() {
var eLeftPos = e.offsetLeft;
//console.log(e.offsetLeft);
e.style.left = (eLeftPos + s) + 'px';
//console.log(e.style.left);
var leftPos = (eLeftPos + s) >= 300
if (leftPos) {
function myInterval1() {
var eTopPos = e.offsetTop;
//console.log(e.offsetLeft);
e.style.top = (eTopPos + s) + 'px';
//console.log(e.style.top);
if ((eTopPos + s) >= 100){
clearInterval(internal1)
}
}
var internal1 = setInterval(myInterval1, 100);
}
if ((eLeftPos + s) >= 300){
clearInterval(internal)
}
}
var internal = setInterval(myInterval, 100);
Try Using CSS methods instead of Javascript. Try this:
CSS Animation from Left to Right
or this: How to animate sliding-in text form left to right

fadeOut() function with setInterval

I'm trying to create a transition effect between images without success.
I'm using this code that works fine, unfortunately the images change without any effect.
var images = [
"https://www.royalcanin.com/~/media/Royal-Canin/Product-Categories/cat-adult-landing-hero.ashx",
"https://www.petfinder.com/wp-content/uploads/2013/09/cat-black-superstitious-fcs-cat-myths-162286659.jpg",
"https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_March_2010-1.jpg"
]
var imageHead = document.getElementById("image-head");
var i = 0;
setInterval(function() {
imageHead.style.backgroundImage = "url(" + images[i] + ")";
i = i + 1;
if (i == images.length) {
i = 0;
}
}, 1000);
https://jsfiddle.net/vvwcfkfr/1/
I've try thousand of solution this week with fadeIn, fadeOut, without any success.
I'm looking to create a transition effect like the slider on the Ryanair's homepage.
Any suggestion? Thanks.
You can use something like transition: background-image 0.3s; in CSS to achieve fade between images, but they have to be the same size. Otherwise there will be also resizing animation.
how about jquery fade in fade out. https://jsfiddle.net/vvwcfkfr/121/
setInterval(function() {
$('#image-head').fadeOut("slow",
function() {
imageHead.style.backgroundImage = "url(" + images[i] + ")";
i = i + 1;
if (i == images.length) {
i = 0;
}
$('#image-head').fadeIn("slow")
}
);
}, 2000);

Resetting jquery varible to lowest possible value that doesn't exist

This script generate divs with cloud images that fly from left to right with random height and intervals. It generally works but it keeps incrementing divs "id" infinitely. I can't figure out how to reset the counter being safe that never two identical "id"s will exist in the same time.
function cloudgenerator(){
var nr=1;
var t1 = 20000;
var t2 = 50000;
function cloud(type,time,nr){
$("#sky").append("<div id=\"cloudFL"+nr+"\" class=\"cloud"+type+"\" ></div>");
setTimeout(function() {
$("#cloudFL"+nr).css({top:Math.floor(Math.random() * 400)+'px'}).animate({
left:'100%',
},time,'linear',function(){$(this).remove();
});
}, Math.floor(Math.random() * t1));
};
function wave(){
var tx = 0;
setInterval(function(){
cloud(1,t1,nr);
nr++;
var n = $( "div.cloud1" ).length;
$( "span" ).text( "There are " + n +" n and "+ tx +" tx")
if(tx < n){tx = n}
else(tx = 1)
},500);
};
wave()};
cloudgenerator()
In the bottom, there is an instruction that checks if number of divs is starting to drop and presents those values in span for debugging.
Quick and easy solutionYou could loop through the id's in JQuery, starting from the lowest number, until you find a JQuery selector that yields 0 results...
var newid = 0;
var i = 1;
while(newid == 0) {
if( $('#cloudFL' + i).length == 0 ) { newid = i; }
else { i++; }
}
JSFIDDLE DEMO
Alternative solution (scalable)
Given that you may have many clouds onscreen at one time, you could try this alternative approach.
This approach creates an array of 'used ids' and the wave function then checks if any 'used ids' are available before creating a new id for the cloud function. This will run quite a bit more efficiently that then above 'quick fix solution' in situations where many clouds appear on screen.
function cloudgenerator(){
var nr=1;
var t1 = 20000;
var t2 = 50000;
var spentids = [];
function cloud(type,time,id){
$("body").append('<div id="' + id + '" class="cloud' + type + '" >' + id + '</div>');
setTimeout(function() {
$('#'+id).css({top:Math.floor(Math.random() * 400)+'px'}).animate({
left:'100%',
},time,'linear',function(){
spentids.push( $(this).attr('id') );
$(this).remove();
});
}, Math.floor(Math.random() * t1));
};
function wave(){
setInterval(function(){
if(spentids.length == 0) {
cloud(1,t1,"cloudFL" + nr);
nr++;
} else {
spentids = spentids.sort();
cloud(1,t1,spentids.shift());
}
},500);
};
wave()};
cloudgenerator()
JSFIDDLE DEMO - ALTERNATIVE
Why not get the timestamp and add this to your id?
If you donĀ“t need the ids i would stick to #hon2a and just add the styling to the class and remove the ids.
And another solution:
You could make a check if ID xyz is used. Like this e.g.
var cloudCount = jQuery('.cloud20000').length + jQuery('.cloud50000').length + 10;
for(var i = 0; i <= cloudCount; i++) {
if(jQuery('#cloudFL' + i).length <= 0) {
nr = i;
return false;
}
}
cloud(1,t1,nr);

Turning Javascript into jQuery

Hi there Stack Overflow,
I'm new at learning jQuery and just trying to condense some sample code down, how would I go about the following.
On mouseover of #navweb, select all elements with a class of .web and then change the background of each of these elements to url(back/"+ i +".png) where i is the JS loop, and then fadeIn these new backgrounds.
Here's the JS i have at current which works (except for the fadeIn)
function showweb() {
for(var i=1; i < 45; i++){
var el = document.getElementById("im"+(i));
if(el && /web/.test( (el ||{}).className)){
el.style.backgroundImage = "url(back/"+ i +"col.png)";}
}
}
function hideweb() {
for(var i=1; i < 45; i++){
var el = document.getElementById("im"+(i));
if(el && /web/.test( (el ||{}).className)){
el.style.backgroundImage = "url(back/"+ i +".png)";}
}
}
I started and got to something like this but it doesn't work, becasue i know its not complete, can you use counters in jQuery?
$('#navweb').mouseover(function(){
var i = 1;
$(".web").each(function(){
$(this).css('background-image', 'url(back/" + i + ".col.png)');
i += 1;
});
});
Many thanks to all replies.
EDIT:
Thanks to all replies, Guffa's proved the most ideal and condensed for my use; I have also added the fadeIn() method but doesn't seem to be triggering on the mouseover?
$('#navweb').mouseover(function(){
$(".web").each(function(){
var i = parseInt(this.id.substr(2));
$(this).css('background-image', 'url(back/' + i + 'col.png)').fadeIn(1000);
});
});
You can get the number from the id of the element:
$('#navweb').mouseover(function(){
$(".web").each(function(){
var i = parseInt(this.id.substr(2));
$(this).css('background-image', 'url(back/' + i + '.col.png)');
});
});
You had a small mistake here: 'url(back/" + i + ".col.png)', it should be like I wrote bellow with single quotes.
$('#navweb').mouseover(function(){
var i = 1;
$('.web').each(function(){
$(this).css('background-image', 'url(back/' + i + '.col.png)');
i += 1;
});
});

Javascript-moving image

How is it posible move an image from one position to other with fadeout?
I hav such functions
for hiding:
function SetOpacity(object,opacityPct)
{
// IE.
object.style.filter = 'alpha(opacity=' + opacityPct + ')';
// Old mozilla and firefox
object.style.MozOpacity = opacityPct/100;
// Everything else.
object.style.opacity = opacityPct/100;
}
function ChangeOpacity(id,msDuration,msStart,fromO,toO)
{
var element=document.getElementById(id);
var opacity = element.style.opacity * 100;
var msNow = (new Date()).getTime();
opacity = fromO + (toO - fromO) * (msNow - msStart) / msDuration;
if (opacity<0)
SetOpacity(element,0)
else if (opacity>100)
SetOpacity(element,100)
else
{
SetOpacity(element,opacity);
element.timer = window.setTimeout("ChangeOpacity('" + id + "'," + msDuration + "," + msStart + "," + fromO + "," + toO + ")",1);
}
}
function FadeOut(id)
{
var element=document.getElementById(id);
if (element.timer) window.clearTimeout(element.timer);
var startMS = (new Date()).getTime();
element.timer = window.setTimeout("ChangeOpacity('" + id + "',500," + startMS + ",100,0)",1);
}
for get current position or next position (by id of image and id of div)
function findPos(e){
var obj = document.getElementById(e);
var posX = obj.offsetLeft;var posY = obj.offsetTop;
while(obj.offsetParent){
posX=posX+obj.offsetParent.offsetLeft;
posY=posY+obj.offsetParent.offsetTop;
if(obj==document.getElementsByTagName('body')[0]){break}
else{obj=obj.offsetParent;}
}
alert(posX+'-'+posY);
}
the first position is position of image, and next - is position of div
The easiest approach with minimal code will be to use jQuery and use the animate function mate.
Ex:
$(".block").animate({"left": "+=50px"}, "slow");
You can use multiple parameters in the brackets like background-color, opacity, etc as you wish to dynamically change the values.
A link for your reference is located at: http://api.jquery.com/animate/
Most javascript animations rely on timer to create the effect of fluid motion. To slide an image across the page, you would set an interval that changed the css position to the right 1px every 5 milliseconds or something of the like. Javascript animation tutorial.
However, animation is most easily accomplished with a library like jquery or many others.

Categories

Resources