How to make background-image fade using JavaScript without jQuery? - javascript

I'm success to use pure JavaScript to make background images fade in/out, but (1)how to make background image show first and start to fade in/out without white part? (2) making background image stay in div block? stuck in here for a week.
I'm trying to using onload event and CSS background-image but both don't work, CSS will make image keep stay in there.
HTML:
<div id="fade"> <span class="bg">Front-Learning</span> </div>
JavaScipt: (before)
var bgslide = [
'image/rotate-img-1.jpg',
'image/rotate-img-2.jpg',
'image/rotate-img-3.jpg'
];
bg_len = 0;
backgroundSlideshow = function bg1() {
if (bg_len == bgslide.length) bg_len = 0;
document.body.style.backgroundImage = 'url(' + bgslide[bg_len++] + ')';
document.body.style.backgroundRepeat ="no-repeat";
document.body.style.backgroundSize = "cover";
document.body.style.backgroundPosition ="center";
document.body.style.height = "400 px";
document.body.style.minWidth = "1000px";
}
window.setInterval(backgroundSlideshow,3000);
window.backgroundImage='url(' + bgslide[0] + ')';
window.onload = document.body.style.backgroundImage='url(' + bgslide[be_len] + ')';
JavaScript (after); it works and what I expect for, but I don't know what the different.
bg_len = 0;
backgroundSlideshow = function () {
if (bg_len == bgslide.length) bg_len = 0;
let fade=document.getElementById("fade");
fade.style.backgroundImage = 'url(' + bgslide[bg_len++] + ')';
}
window.setInterval(backgroundSlideshow,3000);
window.onload = backgroundSlideshow;

Related

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);

JavaScript move character. Change image on clicking right arrow

Hi currently I'm making some RPG game. I want to move my character with arrows. Which is working right now. But I want to change image when I clicking let's say the right arrow. Right now when I click right arrow with this code:
function rightArrowPressed() {
var element = document.getElementById("image1").src = "/img/run_1.png";
element = document.getElementById("image1");
element.style.left = parseInt(element.style.left) + 5 + 'px';
}
The image change's to run_1.png ant it stays like that. Than just the image slides in one pose. How to change the image again when I click right arrow ?
HTML
<img id="image1" src="{{Auth::user()->char_image}}" style="position:absolute;left:0; top:0;height: 45px; image-rendering: -webkit-optimize-contrast;">
You can use a counter variable:
var counter = 0;
function rightArrowPressed() {
counter = (counter === 4) ? 1 : counter+1;
var image = "/img/run_"+counter+".png";
var element = document.getElementById("image1");
element.src = image;
var left = parseInt(element.style.left)+5;
element.style.left = left + "px";
}
And this would make it so that every time you right click, a different image is used.
You can use an arry imeges sources to make a scene
function rightArrowPressed() {
var slides=['/img/run_1.png','/img/run_2.png','/img/run_1.png'];
slides.forEach(slide => {
setTimeout(function(){
var element = document.getElementById("image1").src = slide;
element = document.getElementById("image1");
element.style.left = parseInt(element.style.left) + 5 + 'px';
}, 500);//add a time in screen
});
}

Check to see if background image source exists, with an increasing counter?

I'm trying to have an image gallery on my site, where I have a counter in the background image source, and when a button is clicked, the counter goes up, changing the background image.
But I want the counter to reset, if the image file doesn't exist.
How would I achieve this?
HTML
<div></div>
<button>click</button>
Javascript
var div = document.querySelector("div");
var button = document.querySelector("button");
var counter = 1;
div.style.backgroundImage = "url(image1.jpg)";
button.addEventListener("click", function() {
counter++;
div.style.backgroundImage = "url(image" + counter + ".jpg)";
console.log(counter + " " + div.style.backgroundImage);
if (div.style.backgroundImage === undefined) { counter = 1 } // something like this?
});
There are no JS callbacks for css styles. There is no way to know if a background image loaded successfully or not wait plain JS. It is necessary to load the image twice - once to check.
For that, you can use something like this:
function imageExists(image_url){
var http = new XMLHttpRequest();
http.open('HEAD', image_url, false);
http.send();
return http.status != 404;
}
And refactor your code to pass the image url to the function.
var div = document.querySelector("div");
var button = document.querySelector("button");
var counter = 1;
div.style.backgroundImage = "url(image1.jpg)";
button.addEventListener("click", function() {
counter++;
var imageUrl = "image" + counter;
if (imageExists(imageUrl)){
//Image can be loaded
div.style.backgroundImage = "url(image" + counter + ".jpg)";
console.log(counter + " " + div.style.backgroundImage);
} else {
//Image cannot be loaded
counter = 1;
div.style.backgroundImage = "url(image" + counter + ".jpg)";
}
// something like this?
});

Change background image on pagescroll to create animation? Is canvas more efficient?

I am working on a parallax site in which there are sequence of images (around 400 images). The background images change based on page scroll to create a smoothly moving animation. I managed to get the scrolling working, but when the user scrolls, the change of background images are not smooth (We can see the blank space for a second or so depending on the internet connection). Also, the images are not being cached, the page does a new request every time. How can I optimize this code so that the animation is smooth and it doesn't request a new image every time and uses the cached images. Is it efficient to create the animation in canvas? I tried canvas, but it also makes a new request to images on every scroll. Here is my code using standard background changing based on page scroll:
HTML
<div class="container">
<div id="background-images" class="background-images">
<div class="test"></div>
</div>
</div>
CSS
#background-images{
height: 4000px;
}
.container{
border: 1px solid red;
height: 400px;
overflow: auto;
}
.test{
position: fixed;
top: 0;
left: 0;
z-index: 999;
width: 600px;
height: 600px;
}
Javascript
var $container = $(".container");
var $bgImage = $(".test");
// Attaching the scroll to the background image
$container.scroll(function(event) {
var position = $container.scrollTop();
setBgImage(position);
});
// preload the given total amount of iamges
function preload(totalImages) {
for (var i = 0; i < totalImages; i++) {
$('<img/>')[0].src = getImgUrl(i);
}
}
preload(36); // Preload 36 images, the cache should keep these so we wont't need to load these while we scroll
// Set the background image
function setBgImage(position){
var imageNum;
var lineCount = 0;
imageNum = parseInt(position / 100);
console.log("IMG: " + imageNum + ", Position: " + position);
$bgImage.css("background-image", "url('" + getImgUrl(imageNum) + "')");
}
// Set a placeholder background image
function getImgUrl(num){
return "http://placehold.it/200x200/&text=" + num;
}
JSFiddle: http://jsfiddle.net/4j9u8qtf/1/
You could add all the images hidden and just show the correct one in an actual image element, instead of using css background image. I edited your jsfiddle to demonstrate:
function create(totalImages) {
for (var i = 0; i < totalImages; i++) {
var img = $('<img/>')
img[0].src = getImgUrl(i);
$bgImage.append(img)
}
setBgImage(0)
}
create(37);
function setBgImage(position){
var imageNum;
var lineCount = 0;
imageNum = parseInt(position / 100);
console.log("IMG: " + imageNum + ", Position: " + position);
$bgImage.find("img").hide().eq(imageNum).show()
}
http://jsfiddle.net/y92g7vvL/1/
The best way to preload images is to use the Image constructor like the example below. Using the Image constructor makes it so you don't have to worry about attaching the images anywhere to the document to make them load.
function preload(url) {
var image = new Image();
image.src = url;
}
I updated your Fiddle to use this preload and to not use jQuery for setting the background-image. It works quite well now. All images are preloaded/loaded only once.
$(function () {
var $container = $(".container");
var $bgImage = $(".test");
var bgImage = $bgImage.get(0);
$container.scroll(function (event) {
var position = $container.scrollTop();
setBgImage(position);
});
// preload the given total amount of iamges
function preload(totalImages) {
function fetch(url) {
var image = new Image();
image.src = url;
}
for (var i = 0; i < totalImages; i++) {
fetch(getImgUrl(i));
}
}
preload(36);
function setBgImage(position) {
var imageNum;
var lineCount = 0;
imageNum = parseInt(position / 100);
var url = getImgUrl(imageNum);
bgImage.style.backgroundImage = "url('"+ url +"')";
}
function getImgUrl(num) {
return "http://placehold.it/200x200/&text=" + num;
}
})
Try
html
<div class="container">
<div id="background-images" class="background-images">
<div class="test"></div>
</div>
</div>
<!-- hidden container for `img` elements -->
<div id="imgs"></div>
css
#imgs {
display:none;
}
js
$(function () {
var $container = $(".container");
var $bgImage = $(".test");
$container.scroll(function (event) {
var position = $container.scrollTop();
setBgImage(position);
});
// preload the given total amount of iamges
function preload(totalImages) {
for (var i = 0; i < totalImages; i++) {
$('<img/>', {
"src": getImgUrl(i)
})
// append `img` elements to `#imgs` container
// to `cache` the images ,
// images not requested again at
// `$bgImage` `background-image` adjustments
.appendTo("#imgs");
}
}
preload(36);
function setBgImage(position) {
var imageNum;
var lineCount = 0;
imageNum = parseInt(position / 100);
console.log("IMG: " + imageNum + "
, Position: " + position
, $("#imgs img[src$=" + imageNum + "]"));
// utilize images already in DOM ,
// load `#imgs img` `src` as `$bgImage` `background-image` ,
// from hidden `#imgs` `div`
// images _not_ requested again from server ,
// see `network` tab at console
$bgImage.css("background-image"
, "url('" + $("#imgs img[src$=" + imageNum + "]").attr("src") + "')");
}
function getImgUrl(num) {
return "http://placehold.it/200x200/&text=" + num;
}
});
jsfiddle http://jsfiddle.net/guest271314/bh91g0tv/
The reason that they're being requested over and over is that you're using jQuery background assignment, which reloads the image.
This is silly. You don't need or want jQuery here, and it has side effects you don't understand that are causing your problem.
Just set the X position of the background. Done.
function offset_to(id, posX, posY) {
document.getElementById(id).style.backgroundPosition = posX.toString() + 'px ' + posY.toString() + 'px';
}
To create a smooth effect to your image transition just add css transition in your case:-
.test{
-webkit-transition: all 0.5s ease;
-moz-transition: position 10s;
-ms-transition: position 10s;
-o-transition: position 10s;
transition: all 0.8s ease;
}

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