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

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

Related

I have some JavaScript function that keeps repeating itself, I can't find why

This is code that generates a selected image when a function is run, but the image keeps changing, I want this code to let me have one image and keep it that way instead of it changing randomly every 0.5 - 3 seconds, and I don't know why!
const imageSelector = document.querySelector("#changeHeron")
function spinMachine() {
document.getElementById('spinner').disabled = 'disabled';
spinner.style.transform = "rotate(90deg)";
setInterval(enterBall, 1000)
var protmt = prompt("What's your name?")
alert("Hey there " + protmt + ", " + "its great to see you here")
}
function enterBall() {
var ball = document.getElementById("changeHeron");
ball.style.opacity = "100%";
ball.style.transform = "ScaleX(50%) ScaleY(50%)";
setInterval(liftBall, 1000);
}
function liftBall() {
var ball = document.getElementById("changeHeron");
ball.style.transform = "translateY(-250%)";
ball.style.transform = "ScaleX(200%) ScaleY(200%)";
ball.style.top = "40%";
setInterval(changeImage, 1500);
}
function changeImage() {
var images = ["./Images/Football.png", "./Images/Mousetache.png", "./Images/OG.svg"];
var randomNum = Math.floor(Math.random() * images.length);
var ball = document.getElementById("changeHeron");
ball.src = images[randomNum];
ball.style.borderRadius = "5%";
ball.style.backgroundColor = "white";
}
I found that you can place the images varible outside and change it inside when the code has ran so that the rest can just work outside of this problem

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

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;

Loading bar while image loads from getElementById

Below I have some code for a comic website I'm maintaining. When you click various buttons or select a page from the drop down menu the image changes to the corresponding image. However the image remains on the previous image until the new one has loaded. Is there any way I can add a loading bar or one of the spinning circle things until it has happened?
FYI, I'm not heaps advanced with JS, and this is my own code creation. Help much appreciated.
// Drop Down Menu, next and previous buttons
// Buttons
$(document).ready(function () {
var dd = $('#HailComic');
var max_len = dd.find('option').length;
$('#nextpage').click(function () {
var x = dd.find('option:selected').index();
if (max_len == x + 1) x = -1;
dd.find('option').eq(x + 1).prop('selected', true);
document.getElementById("hail_image").src="images/comic/hail_" + HailComic.options[HailComic.selectedIndex].value + ".jpg";
});
$('#previouspage').click(function () {
var x = dd.find('option:selected').index();
if (0 == x + 1) x = max_len;
dd.find('option').eq(x - 1).prop('selected', true);
document.getElementById("hail_image").src="images/comic/hail_" + HailComic.options[HailComic.selectedIndex].value + ".jpg";
});
$('#lastpage').click(function () {
var x = max_len;
dd.find('option').eq(x - 1).prop('selected', true);
document.getElementById("hail_image").src="images/comic/hail_" + HailComic.options[HailComic.selectedIndex].value + ".jpg";
});
$('#firstpage').click(function () {
dd.find('option').eq(0).prop('selected', true);
document.getElementById("hail_image").src="images/comic/hail_001.jpg";
});
});
// List Changing
$(document).ready(function(){
// Select
var changeHailImage = function () {
document.getElementById('hail_image').src = "images/comic/hail_" + this.options[this.selectedIndex].value + ".jpg"
}
var HailList = document.getElementById('HailComic');
HailList.addEventListener('change', changeHailImage, false);
});
You an use img.load() function to achieve this. Please check the pen http://codepen.io/anon/pen/VvwWWj
var changeHailImage = function () {
document.getElementById('hail_image').src = 'loading.gif';//get a loading image
var img = new Image();
img.src = "images/comic/hail_" + this.options[this.selectedIndex].value + ".jpg";
img.onload = function () {
document.getElementById('hail_image').src = img.src;
}
}

Weird counter behaviour when integrate on script

Ok i have finish this code
http://jsfiddle.net/xHL35/9/
I just made some css changes, and rename image_wrap to image_wrap_galeria
here http://queretaro.orsilin.com.mx/index.php?page=item/view/15/Probando
But the counter is really not counting the imgs on .items.
I really tried to debug this one. i cant find the mistake
Here is my JS code.
<script>
$(function() {
$(".scrollable").scrollable();
var scrollapi = $(".scrollable").data('scrollable');
$(".items img").click(function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("t_", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap_galeria").fadeTo("medium", 0.5);
var wrap2 = $("#mainim");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap2.find("img").attr("src", url);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").click();
$("img[rel]").overlay({
// some mask tweaks suitable for modal dialogs
mask: {
color: '#ebecff',
loadSpeed: 200,
opacity: 0.9
},
closeOnClick: true,
onBeforeLoad: function() {
var items = $('.items'),
count = items.find("img").length,
current = items.find('.active'),
currentIndex = current.index("img");
$("#imageCounter").html( currentIndex+" of "+count);
}
});
//NExt BTN
$(".nextImg").click(function(){
// Count all images
var items = $('.items'),
images = items.find('img'),
count = images.length,
currentImage = items.find('.active'),
currentImageIndex = images.index(currentImage),
next = $(images.get(currentImageIndex + 1)),
nextImageIndex = images.index(next);
if ( currentImageIndex === (count - 1) ){
next = $(images.get(0));
nextImageIndex = images.index(next);
}
if (nextImageIndex === 0) {
scrollapi.begin(200);
} else if ( nextImageIndex % 4 === 0 && nextImageIndex > 0) {
scrollapi.next(200);
}
// Get the current image number
var current = $(next.index("img"));
var nextUrl = next.attr("src").replace("t_", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap_galeria").fadeTo("medium", 0.5);
var wrap2 = $("#mainim");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", nextUrl);
wrap2.find("img").attr("src", nextUrl);
};
// begin loading the image from www.flickr.com
img.src = nextUrl;
$("#imageCounter").html((nextImageIndex + 1) +" of "+count);
// activate item
$(".items img").removeClass("active");
next.addClass("active");
});
//PREV BTN
$(".prevImg").click(function(){
// Count all images
var items = $('.items'),
images = items.find('img'),
count = images.length,
currentImage = items.find('.active'),
currentImageIndex = images.index(currentImage),
prev = $(images.get(currentImageIndex - 1)),
prevImageIndex = images.index(prev);
// var prev = $(".items").find(".active").prev("img");
if(currentImageIndex === 0){
prev = $(images.get(count-1));
prevImageIndex = images.index(prev);
}
if(prevImageIndex === (count - 1)) {
// We have reached the end - start over.
scrollapi.end(200);
} else if ( (prevImageIndex + 1) % 4 === 0 ) {
scrollapi.prev(200);
}
// Get the current image number
var current = (prev.index("img"));
var prevUrl = prev.attr("src").replace("t_", "");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap_galeria").fadeTo("medium", 0.5);
var wrap2 = $("#mainim");
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", prevUrl);
wrap2.find("img").attr("src", prevUrl);
};
// begin loading the image from www.flickr.com
img.src = prevUrl;
$("#imageCounter").html((prevImageIndex + 1) +" of "+count);
// activate item
$(".items img").removeClass("active");
prev.addClass("active");
});
});
</script>

Placing multiple images in HTML at once with JavaScript

EDIT : Here's another problem: I can't define each picture's Z-index with the for loop.
function placeImage(x) {
var div = document.getElementById("div_picture_right");
div.innerHTML = ""; // clear images
for (counter = 1; counter <= x; counter++ ) {
var image = document.createElement("img");
image.src = "borboleta/Borboleta" + counter + ".png";
image.width = "195";
image.height = "390";
image.alt = "borboleta" + counter;
image.id = "imagem" + counter;
image.position = "relative";
image.style.zIndex = counter;
div.appendChild(image);
}
};
window.onload = function () {
placeImage(20);
};
<body>
<div id="div_wrapper">
<div id="div_header">
<h1>First Project</h1>
</div>
<div id="div_picture">
<div id="div_picture_left"></div>
<div id="div_picture_right"></div>
</div>
</div>
</body>
When checking FireBug, I get this:
Error: image corrupt or truncated
Looks like your code is executing before the div exists on the page. You shouldn't try to get a handle on an element in the DOM until it is fully loaded. You can define your function outside of window.onload, but keep your call within window.onload, example:
function placeImage(x)
{
var div = document.getElementById("div_picture_right");
div.innerHTML = ""; // clear images
for (counter=1;counter<=x;counter++) {
var imagem=document.createElement("img");
imagem.src="borboleta/Borboleta"+counter+".png";
div.appendChild(imagem);
}
}
window.onload = function() {
placeImage(48);
};
I also added a small improvement which is to get the handle on the div and store in a variable once, instead of getting a new handle on each iteration.
Try this:
var placeImage = function(x) {
var img="";
for (var counter = 1; counter <= x; counter++ ) {
img += '<img src="borboleta\Borboleta'+counter+'.png" alt="" />';
}
document.getElementById("div_picture_right").innerHTML = img;
};
placeImage(48);
With this code, there's only 1 DOM operation rather than 48.
Also make sure if you have an element with the said ID (div_picture_right).
If you want to change the divs' z-index dynamically, set their position attribute to "absolute" instead of "relative". It makes more sense that way.

Categories

Resources