I am using jQuery and this code:
$(window).load(function()
{
var i =0;
var j =0;
var images = ['img/TopSlider/car_and_cycle.jpg', 'img/TopSlider/cafe.jpg'];
var image = $('#box');
var titles = ['Rent Car and Bikes', 'Cafes and Restaurants'];
//Initial Background image setup
image.css('background-image', 'url(img/TopSlider/cafe.jpg)');
//Change image at regular intervals
setInterval(function()
{
image.fadeOut(1000, function ()
{
image.css('background-image', 'url(' + images [i++] +')');
image.fadeIn(1000);
$("#text2").text(titles [j++]);
});
if(i == images.length)
{
i = 0;
j = 0;
}
}, 5000);
});
but after some time (maybe 10 min), when I go back to the tab in Safri, I don't see the background image. But at start and maybe during 1 min it works perfect.
Related
I have built a code which change pictures every 5 second using setinterval() and everytime when a picture is changes, it will show up with it's opacity growing from 0 to 1, using setinterval() as well.
It all works excellently, but there is a single problem which I can find the way to fix it. The problem is that after I start the page, if I move to a differend tab, if I come back in a minute, it all goes craze and the opacity is growing too fast and more then once before a picture is changed.
Here is the code:
var images = [], x = 0, t = 0, timerid, s = 0;
images[0] = "Images/" + location.pathname.substring(1, location.pathname.length - 5) + "2.jpg";
images[1] = "Images/" + location.pathname.substring(1, location.pathname.length - 5) + ".jpg";
function ChangeOpacity() {
img = document.getElementById("img");
s += 0.003;
t = s.toString();
img.style.opacity = t;
if (img.style.opacity>=1) {
s = 0;
clearInterval(timerid);
}
}
function SwitchImage() {
img = document.getElementById("img");
img.src = images[x];
img.style.opacity = 0;
timerid = setInterval('ChangeOpacity()', 1);
x++;
if (x >= images.length)
x = 0;
}
function StartFun() {
setInterval('SwitchImage()', 5000);
}
You could add a window.onblur and window.onfocus function. Each time the tab loses focus (onblur) you could clear the interval and restart it when the tab gets focused again (onfocus).
More about focus on tabs
Edit:
Restarting the interval is not necessary in all cases.
js windows animate scrolltop to div class is scrolling right to to the bottom of the div
js
$(document).ready(function () {
$('html, body').animate({
scrollTop: $('.tariff').offset().top
}, 'slow');
});
it is scrolling right to the bottom of div class 'tariff'. I want it to scroll and stop at the top of the div.
Did a lot of googling. Don't know where I am going wrong.
EDIT
I think it may have something to do with my external js.js file. Something here is probably effecting the animate scrolling height. Because if I omit this file,
it scrolls properly to the top of the div.
But I don't know what is interfering here.
js.js
$('document').ready(function(){
$('#smshare').click(function() {
$('#smp').slideToggle('fast');
$('#smp').load('social-media-share.php');
});
$('#offer,#orderlink').click(function()
{
$('#order').fadeIn('fast');
$('html, body').animate({
scrollTop: $("#order").offset().top
}, 2000);
$('.scrolltop').fadeIn('fast');
$('.aboutus,.tariff,.services,.contactus,.logged_order,.pers_dets,.clothes_submitted,.locations_list').fadeOut('fast');
});
$('.scrolltop').click(function(){
$('#order').fadeOut('fast');
$('html, body').animate({
scrollTop: $(".header").offset().top
}, 2000);
$('.scrolltop').fadeOut('fast');
});
$('#svl').click(function()
{
$('html, body').animate({
scrollTop: $(".service_locations").offset().top
}, 2000);
});
$('.more1').click(function() {
$('.more_dry_cleaning').slideToggle('fast');
$('.more1').fadeOut('fast');
});
$('.less1').click(function() {
$('.more_dry_cleaning').fadeOut('fast');
$('.more1').fadeIn('fast');
});
var valid=0;
$('form[name=orderform]').submit(function(e) {
// alert('Got you!');
$('.clothesqty').each(function(){
// alert('Got you!');
if($(this).val() != 0) {valid+=1;}
});
if(valid!=0){
// e.preventDefault();
// alert(valid + " inputs have been filled");
return true;
}
else {
e.preventDefault();
//alert('Houston we have contact!');
alert("error: you must fill in at least one field");
return false;
}
});
var oblen=Object.keys(item).length;
var zero=0;
var cloth = "";
var i;
var it=1;
var totitems=0;
var tot=0;
var totcost=0;
var itemid="";
var itemclass="";
var totval=0;
for (var key in item) {
if (!item.hasOwnProperty(key)) {
//The current property is not a direct property of p
continue;
}
var k=key;
var v=item[key];
// alert(v);
cloth = k.replace(/ |-|&|\//g, '').toLowerCase();
itemid="#" + cloth;
itemclass="#" + cloth + "cost";
// alert(v+"/"+itemid);
$(itemid).keyup((function (id, cls,itm,val) {
return function () {
var x = $(id).val();
if(x!=0){
itemtot=x * val;
// alert(itm+"->"+itemtot + "=" + x + "x" + val);
$(cls).css("background-color", "#446666").css("padding","3px").css("color","white").css("width","60px").html("Rs." + itemtot);
}else{
$(cls).css("background-color", "#446666").css("padding","3px").css("color","white").css("width","60px").html("Rs." + zero);
}
}
} (itemid, itemclass,cloth,v)));
}
$("input").each(function() {
$(this).keyup(function(){
// calculateCost();
calculateSum();
});
});
});
//Totals
function calculateSum() {
var sum = 0;
var totcost=0;
//iterate through each textboxes and add the values
$("input").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0 && this.value.length<=3) {
sum += eval(parseInt(this.value));
}
});
$("div.ittot").each(function() {
var tots=0;
var str=$(this).text();
var thenum = str.replace( /^\D+/g, '');
var tots = parseInt(thenum,10);
//add only if the value is number
//if(!isNaN(tots) && tots.length!=0) {
totcost += tots;
//}
});
// alert(totcost);
$("#totalcost").css("background-color", "green").html("<div style='float:left;margin-left:5px'><span style='font-weight:700'>Total Cost : </span>Rs."+ totcost + "</div><div style='float:right;margin-right:5px'><span style='font-weight:700'>Total Items : </span>" + sum + "</div><div style='clear:both'></div>");
}
//slider2
var myPicIndex = 0;
picCarousel();
function picCarousel() {
var i;
var x = getElementsByClassName("myPicSlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myPicIndex++;
if (myPicIndex > x.length) {myPicIndex = 1}
x[myPicIndex-1].style.display = "block";
setTimeout(picCarousel, 3000); // Change image every 2 seconds
}
function getElementsByClassName(className) {
var found = [];
var elements = document.getElementsByTagName("*");
for (var i = 0; i < elements.length; i++) {
var names = elements[i].className.split(' ');
for (var j = 0; j < names.length; j++) {
if (names[j] == className) found.push(elements[i]);
}
}
return found;
}
//slider1
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 3000); // Change image every 2 seconds
}
function getElementsByClassName(className) {
var found = [];
var elements = document.getElementsByTagName("*");
for (var i = 0; i < elements.length; i++) {
var names = elements[i].className.split(' ');
for (var j = 0; j < names.length; j++) {
if (names[j] == className) found.push(elements[i]);
}
}
return found;
}
EDIT 2
I have further narrowed down the problem to the slider2 JS functions which seem to be a problem. Because if I remove the slider html which i have put in a slider2.php file and am including into the tariff.php file, then the scroll behaves properly.
slider2.php
<div style="width:100%;margin:0 auto">
<img class="myPicSlides" src="images/header/clothes-drying-on-line-iv.jpg" alt="Laundry Clothes Drying">
<img class="myPicSlides" src="images/header/new/shirts-on-line-iv.jpg" alt="Laundry Foam">
<img class="myPicSlides" src="images/header/iron-and-clothes-iv.jpg" alt="Iron Clothes">
<img class="myPicSlides" src="images/header/woollens-iv.jpg" alt="Woollens Laundry">
<img class="myPicSlides" src="images/header/shirts-on-hanger-iv.jpg" alt="Laundry Shirts mylaundrywala">
</div>
EDIT 3
I believe the animate function is taking into consideration the heights of the images in the slider and adding them up ! How to resolve that ?
If you want to reach to the top of window, please use this:
$("html, body").animate({
scrollTop: 0
}, 500);
$('.tariff').offset().top gives position distance between top of body and top of div with class "tariff".
As a result, it covers that much distance when scrolled.
Please try like this.
Use this code.
$(document).ready(function () {
$('html, body').animate({
scrollTop: $('.tariff').offset().top + $('.tariff').height()
}, 'slow');
});
Check the fiddle its is working for me there. Let me know if this helps.
$("#scroll").click(function(e) {
$('html, body').animate({
scrollTop: $('.tariff').offset().top
}, 'slow');
});
Fiddle
Since I realized that it was the heights of the images in the slider which was being laid out one below the other by html rather than fading in and out one by one when javascript is called (which has a fractional delay), the animate function registers the page height including all the heights of the images ! And scrolls keeping those heights in consideration. That is why it was scrolling right down to the bottom. Instead of top of the div.
Though I was not able to find a js solution to the real problem, I managed to find a work around.
Finally, what I did was to delay the slider images loading by using 'load' function. And placed one static image there till slider loaded and then faded the static image out after slider images loaded.
During this period, the animate function picks up only the height of that one static image which is actually the height that div should have after all images have loaded.
Now the animate scroll function is scrolling to the top of the relevant div.
Thanks all for your efforts to help
Vanilla way
var el = document.getElementById('myelement');
el.scrollTop = el.scrollHeight;
I was looking for a way to change the background of a div using jQuery and I found this question:
change background image jquery
I made it and it's working. But, there's a way to ease the process? Like an fade-in/out?
Sorry for my english. And thank you for your time.
UPDATE:
.branding{
min-height:530px;
background-image:url(../images/brandings-0.jpg);
background-repeat:no-repeat;
background-position:center;
}
var newBg = [
'site/assets/images/brandings-1.jpg',
'site/assets/images/brandings-2.jpg',
'site/assets/images/brandings-3.jpg'];
var i = 0;
var rotateBg = setInterval(function(){
i++;
if(i > 2)
i=0;
$('.branding').css({backgroundImage : 'url(' + newBg[i] + ')'});
}, 5000);
<div class="branding"></div>
Try the following fiddle I created for you.
http://jsfiddle.net/ujyjcfea/1/
var i = 0;
var newBg = [
'http://lorempixel.com/output/animals-q-c-640-480-2.jpg',
'http://lorempixel.com/output/animals-q-c-640-480-1.jpg',
'http://lorempixel.com/output/animals-q-c-640-480-4.jpg'];
var image = $('.branding');
image.css('background-image', 'url(http://lorempixel.com/output/animals-q-c-640-480-2.jpg)');
setInterval(function () {
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + newBg[i++] + ')');
image.fadeIn(1000);
});
if (i == newBg.length)
i = 0;
}, 5000);
http://www.programming-free.com/2013/12/change-background-image-jquery.html
demo - http://jsfiddle.net/victor_007/RyGKV/643/
var i = 0;
var images = ['http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-5.jpg', 'http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-2.jpg', 'http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-1.jpg'];
var image = $('#slideit');
image.css('background-image', 'url(http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-5.jpg)'); //Initial Background image setup
setInterval(function () {
image.fadeOut(1000, function () {
image.css('background-image', 'url(' + images[i++] + ')');
image.fadeIn(1000);
});
if (i == images.length) i = 0;
}, 5000);
I have two images stacked. With setInterval(), the top one fades away, exposing the second. Then the top image switches to the bottom's src while invisible, and becomes opaque again. The second image changes to the next image and waits for the setInterval() to fade the top image and do it all over again.
It all works great, except the first time around; There's no fade. What am I not seeing?
This happens on all firefox and chrome and I assume all others.
HTML
<script type="text/javascript">
setInterval('swapImage()', 5000);
var galleryCount = 3;
</script>
...
<img id="image" src="images/gallery/01.jpg" />
<img id="imagenext" src="images/gallery/02.jpg" />
Javascript
function swapImage(imageToFadeID)
{
$("#image").animate
(
{ "opacity": "0" },
"slow",
"linear",
changeImage()
);
};
var i = 1;
function changeImage()
//counter +1
{
i = i + 1;
//add "0" to image number "j" if less than 10.
if (i < 10)
{
var j = "0" + i;
}
else
{
j = i;
}
//change top image to match bottom
var topImage = document.getElementById("imagenext").src;
document.getElementById("image").src = topImage;
//make top image reappear
document.getElementById("image").style.opacity = '1';
//change out bottom image to next
var btmImage = "images/gallery/" + j + ".jpg";
document.getElementById("imagenext").src = btmImage;
//reset counter if at end
if (i > galleryCount - 1)
{
i = 0;
}
}
I looks like you're invoking changeImage instead of passing it as a callback to animate:
Wrong:
function swapImage(imageToFadeID)
{
$("#image").animate
(
{ "opacity": "0" },
"slow",
"linear",
changeImage() // <--- !!! Remove the parentheses from this line!
);
};
Right:
function swapImage(imageToFadeID)
{
$("#image").animate
(
{ "opacity": "0" },
"slow",
"linear",
changeImage
);
};
I would like to make an image change after 30 seconds. The javascript I'm using looks like this:
var images = new Array();
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
var x = 0;
function changeImage() {
document.getElementById("img").src=images[x];
x++;
}
HTML:
<img id="img" src="startpicture.jpg">
Now I haven't tested this one yet, but if my calculations are correct it will work :)
Now what I also want is to make a "fading transition" and I would like the changing of images to loop (it restarts after all the images have been shown).
Do any of you guys know how to do that?
I agree with using frameworks for things like this, just because its easier. I hacked this up real quick, just fades an image out and then switches, also will not work in older versions of IE. But as you can see the code for the actual fade is much longer than the JQuery implementation posted by KARASZI István.
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length) {
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()", 30000);
}
function fadeImg(el, val, fade) {
if(fade === true) {
val--;
} else {
val ++;
}
if(val > 0 && val < 100) {
el.style.opacity = val / 100;
setTimeout(function(){ fadeImg(el, val, fade); }, 10);
}
}
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
You should take a look at various javascript libraries, they should be able to help you out:
mootools
jQuery
Dojo Toolkit
prototype
All of them have tutorials, and fade in/fade out is a basic usage.
For e.g. in jQuery:
var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
$img.fadeOut(speed, function() {
$img.attr("src", images[(++i % images.length)]);
$img.fadeIn(speed);
});
}, 30000);
setInterval function is the one that has to be used.
Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.
CODE:
var im = document.getElementById("img");
var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;
function changeImage()
{
im.setAttribute("src", images[index]);
index++;
if(index >= images.length)
{
index=0;
}
}
setInterval(changeImage, 30000);
Just use That.Its Easy.
<script language="javascript" type="text/javascript">
var images = new Array()
images[0] = "img1.jpg";
images[1] = "img2.jpg";
images[2] = "img3.jpg";
setInterval("changeImage()", 30000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
if (images.length == x)
{
x = 0;
}
}
</script>
And in Body Write this Code:-
<img id="img" src="imgstart.jpg">