Javascript: Reset a counter if an image does not exist? - javascript

I've made a javascript function to display a number of images in a folder one after another. I'd like to automatically reset my counter if the next image doesn't exist. Eliminating the necessity of passing the number of images in a folder to the function.
<!DOCTYPE html>
<html>
<title>Slideshow</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</html>
<body>
<div id="output" class="slides"></div>
<script type="text/javascript">
var pageURL = window.location.search.substring(1);
var pic_info = pageURL.split('?');
var pic_path = pic_info[0] + '/';
var pic_max_number = 3;
var pic_number = 0;
pic_slideshow();
function pic_slideshow() {
pic_number++;
if (pic_number > pic_max_number) {
pic_number = 1
}
document.getElementById('output').innerHTML = '<img src="' + pic_path + pic_number + '.jpg">';
setTimeout(pic_slideshow, 3000); // Change image every 3 seconds
}
</script>
</body>
</html>
I'D like to add an error handling function, that resets the pic_number variable to 1 to restart the loop. Any ideas using pure javascript?
Thanks...

You can use the onerror attribute of the image tag to reset the global variable pic_number to 1, and load image 1.jpg in place of the missing image.
Change your innerHTML value to:
document.getElementById('output').innerHTML =
'<img src="' + pic_path + pic_number + '.jpg"'
+ ' onerror="pic_number=1; this.src=\'' + pic_path + '1.jpg\'">';
If you add an event listener in your Javascript code you'll need to modify how you're updating your pics.
In your HTML add an img tag:
<div id="output" class="slides"><img src=""></div>
And in your script body add the onerror event listener to that img element:
document.querySelector('#output img').onerror = function (evt) {
pic_number = 1;
evt.target.src = pic_path + '1.jpg';
}
And in your pic_slideshow function change the src value of the existing image element rather than creating a new one:
document.querySelector('#output img').src = pic_path + pic_number + '.jpg';
An event listener will get lost each time you change the #output div innerHTML.
Alternatively you can use the addEventListener method:
document.querySelector('#output img').addEventListener('error', function (evt) {
pic_number = 1;
evt.target.src = pic_path + '1.jpg';
})

You could sense onerror in the img element, or add an eventlistener via JavaScript and reset the counter.
See MDN

Related

Make a new image appear by clicking on the previous image

I want to write a code in which when you click on an image another image appears. After that when you click on the new image, another one appears, and so on.
I wrote this code which works for the first image. I can't figure out how to define the appeared images as inputs.
var i = 1
function addimage() {
var img = document.createElement("img");
img.src = "images/d" + i + ".jpg";
document.body.appendChild(img);
}
function counter() {
i = i + 1
}
<input type="image" src="images/d1.jpg" onclick="addimage(); counter();">
Attach an onclick function to the new image, with the same code as in your input tag:
var i = 1
function imageClick() {
if (! this.alreadyClicked)
{
addimage();
counter();
this.alreadyClicked = true;
}
}
function addimage() {
var img = document.createElement("img");
img.src = "http://placehold.it/" + (200 + i);
img.onclick = imageClick;
document.body.appendChild(img);
}
function counter() {
i = i + 1
}
<input type="image" src="http://placehold.it/200" onclick="imageClick();">
To add an event handler to an element, there are three methods; only use one of them:
=> With an HTML attribute. I wouldn't recommend this method because it mixes JS with HTML and isn't practical in the long run.
<img id="firstImage" src="something.png" onclick="myListener(event);" />
=> With the element's attribute in JS. This only works if you have a single event to bind to that element, so I avoid using it.
var firstImage = document.getElementById('firstImage');
firstImage.onclick = myListener;
=> By binding it with JavaScript. This method has been standardized and works in all browsers since IE9, so there's no reason not to use it anymore.
var firstImage = document.getElementById('firstImage');
firstImage.addEventListener("click", myListener);
Off course, myListener needs to be a function, and it will receive the event as its first argument.
In your case, you probably don't want to add another image when you click on any image that isn't currently the last. So when a user clicks on the last image, you want to add a new image and stop listening for clicks on the current one.
var i = 1;
function addNextImage(e) {
// remove the listener from the current image
e.target.removeEventListener("click", addNextImage);
// create a new image and bind the listener to it
var img = document.createElement("img");
img.src = "http://placehold.it/" + (200 + i);
img.addEventListener("click", addNextImage);
document.body.appendChild(img);
// increment the counter variable
i = i + 1;
}
var firstImage = document.getElementById("firstImage");
firstImage.addEventListener("click", addNextImage);
Try on JSFiddle
On a side note: while JavaScript does support omitting some semi-columns it's considered a better practice to put them, and it will avoid small mistakes.

Image swapping when a variable changes

I have an html page that has one image object.
I am trying to write some JavaScript but something isn't working in the script. I have a piece of script that reads a variable and if the variable 'e' is equal to 1, then one image appears. If 'e' is anything other number then image 2 appears. For now, 'e' is static, but it will be dynamic.
How do you change an image dynamically based off a variable?
Any help is most appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<body onload="changei()">
<img id="im1" src="Images/lion1.jpg" width="100" height="180" style="display:show">
<p> hello</p>
<script>
function changei() {
var e = 0;
changei(e);
// something changed e in e = 0;
change(e);
function changei(e) {
var loc = '';
if (image.src.match("lion1")) {
image.src = "Images/lion1.jpg";
} else {
image.src = "Images/lion2.jpg";
}
$('#im1').attr("src",loc); // change image source
}
</script>
</body>
</html>
You can use jQuery to change image source. Your function have e inside, pass it as parameter and you can change the image where you want just by calling the function with the corresponding value.
var e = 1;
changei(e);
// something changed e in e = 0;
changei(e);
function changei(e) {
var loc = '';
if (e==1) {
loc = "Images/lion1.jpg";
} else {
loc = "Images/lion2.jpg";
}
$('#im1').attr("src",loc); // change image source
}
Example: You can attach an event to an input, keyup and every time you press a key in that input the image will change based on what you entered.
changei(1); // when entering in page set src
$('#eInput').keyup(function(){ // when something was inserted on input
var e = $(this).val();
changei(e);
});
function changei(e) {
var loc = '';
if (e==1) {
loc = "http://images.math.cnrs.fr/local/cache-vignettes/L256xH256/section1-original-0f409.png";
} else {
loc = "http://www.data-compression.com/baboon_24bpp.gif";
}
$('#im1').attr("src",loc); // change image source
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="eInput" />
<img id="im1" src="Images/lion1.jpg" style="display:show">
You can do two things:
You will be changing value of the variable e in some function then simply create a function to change image as follows and call it.
function changeImg(e){
if(e==1)
//your code for image 1
else
//code for image 2
}
Call this function right after you change e.
Use the setInterval() function. e.g.
setInterval(5000,function(){
changeImg(e);
});
Although, you should keep in mind that you need to make e global for case 2

How to get JQuery to swap picture prior to page being displayed

I've got the following script which swaps the source of an image. However currently this happens after the page loads so the user experiences a split second of seeing one picture before it switches to the correct image.
<script>
window.onload = function () {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
$("#pictureDiv img").attr("src", "/Content/Images/" + winnerName + ".jpg");
};
</script>
How can I get the image to switch before loading?
Note I've also tried:
<script>
$(function() {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
$("#pictureDiv img").attr("src", "/Content/Images/" + winnerName + ".jpg");
});
</script>
but this results in the same thing occurring
Both of the window.onload or jQuery's $(function()... functions are only called when the page is fully loaded.
The closest you could get is to add the function to the images onload handler.
<img src="..." onload="function() {...}">
But I suspect the same will still occur.
If the image's src needs to be set using javascript then you could try dynamically creating the image and adding it in where you need it, using something like the following.
$(function() {
var winnerName = $("#leaderboard tr td:eq(1)").text().trim();
var imgElement = $('<img>').attr("src", "/Content/Images/" + winnerName + ".jpg");
$("#pictureDiv").append(imgElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pictureDiv"></div>

How to add while loop to randomizer

I am trying to learn JavaScript and have made a website which randomizes gifs onclick from an array.
What I would like to do now is insert a while loop so that it will compare the currentgif to the next randomized image so no duplicates are shown but I can't quite figure out what I am doing wrong, most likely a syntax issue.
HTML
<!DOCTYPE html>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<html>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="js/rand.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<head>
<title>Randomizer</title>
</head>
<body>
<p>This image is random</p>
<a href="#" class="click">
<section>
<img>
<script>
getRandomImage()
</script>
</img>
</section>
</a>
</body>
</html>
JavaScript
var randomImage = new Array();
randomImage[0] = "images/1.gif";
randomImage[1] = "images/2.gif";
randomImage[2] = "images/3.gif";
function getRandomImage() {
var number = Math.floor(Math.random()*randomImage.length);
document.write('<img src="'+randomImage[number]+'" />');
}
$(function() {
$('a.click').click(function(e) {
e.preventDefault();
var number = Math.floor(Math.random()*randomImage.length);
$(this).html('<img src="'+randomImage[number]+'" />');
});
});
You first need to get which image it is:
function returnImgNum(){
var imgNum = parseInt($('img').attr('src').split("/")[1].replace('.gif', ""));
return imgNum;
}
Then make a loopable function (or just make a while loop, I like doing it this way)
function placeRand(number){
if(number != returnImgNum()){
document.write('<img src="'+randomImage[number]+'" />');
} else {
placeRand(number){
}
}
Then add that comparator loop to your function:
function getRandomImage() {
var number = Math.floor(Math.random()*randomImage.length);
placeRand(number);
}
var random_images_array = ['smile.gif', 'frown.gif', 'grim.gif', 'bomb.gif'];
function getRandomImage(imgAr, path) {
path = path || 'images/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr); document.close();
}
Check out this link. It tells you everything you need to know.
http://www.dyn-web.com/code/basics/random_image/random_img_js.php
Create array, put inside all image names (or their indexes if it's better for you) and then use something like this:
var images = ["/first.png", "/second.png", "/third.png", "/fourth.png", "/fifth.png"];
function takeImage() {
// if there is no more images in array, do something or return placeholder image
//if (!images.length) doSomething();
var image = images.splice(Math.floor(Math.random() * images.length), 1);
return image[0];
}
Basically, this function on each call will return one random image name (or index if you want) until there will be no images left in this array.
Simple, you save the last image out of the function. This makes a global variable. A global variable is a variable that exists in all functions, as a local variable only exists in the function itself (other functions cant use it).
// Define it outside of the function so the next time the called
// function gets it still has a value:
var lastNumber=0;
var imagesLength = randomImage.length; // don't recalc the amount of images every time
function getRandomImage(){
var number=0; // start a local variable
while( number == lastNumber){
number = Math.floor(Math.random()*imagesLength );
}
document.write('<img src="'+randomImage[number]+'" />');
}
To expand a bit on the local/global variables, lastNumber is global and can therefor be accessed in the function. var number however is local, it only exists in the function, console.log(number); outside the function would be undefined
To make a suggestion for improvement, document.write is best to be avoided. Browsers don't like them (*can't find doc's to support, feel free to edit), pre-create an image, even if its blank:
<img id="RandomImage" src="transparant.png" />
Now you make a global variable (this can only be done if the javascript is loaded after the image in the source, or with a document ready) to store the image, and use that:
// save reference to image, global (before the function):
var Image2Random = document.getElementById('RandomImage');
// place this instead of the document write.
Image2Random.src = randomImage[number];
This will be a lot faster. Javascript now knows what image to change, it doesn't have to create a new one every call (inserting elements to the DOM is expensive in resources), and the .src is really fast to change just the source.

Changing JS code from clicking image to clicking link

I found the following JS online, which functions like:
If an image is clicked, open the image in new window and prompt for print. Once printed the window closes. I need this script modified to click a print link it prints an image then closes the new image window. So I want to change from clicking the image itself to clicking a link that says print image.
Here is the code:
<script type="text/javascript">
/* <![CDATA[ */
function makepage(src)
{
// We break the closing script tag in half to prevent
// the HTML parser from seeing it as a part of
// the *main* page.
return "<html>\n" +
"<head>\n" +
"<title>Temporary Printing Window</title>\n" +
"<script>\n" +
"function step1() {\n" +
" setTimeout('step2()', 10);\n" +
"}\n" +
"function step2() {\n" +
" window.print();\n" +
" window.close();\n" +
"}\n" +
"</scr" + "ipt>\n" +
"</head>\n" +
"<body onLoad='step1()'>\n" +
"<img src='" + src + "'/>\n" +
"</body>\n" +
"</html>\n";
}
function printme(evt)
{
if (!evt) {
// Old IE
evt = window.event;
}
var image = evt.target;
if (!image) {
// Old IE
image = window.event.srcElement;
}
src = image.src;
link = "about:blank";
var pw = window.open(link, "_new");
pw.document.open();
pw.document.write(makepage(src));
pw.document.close();
}
/* ]]> */
</script>
<img src="fortune.jpg" onclick="printme(event)" />
I do not know any JS so I apologize. I only do php/mysql.
Best Regards!
Jim.
<img src="someurl.jpg" id="imgid' />
Print the image
function printme(id)
{
var src = document.getElementById(id).src;
var link = "about:blank";
var pw = window.open(link, "_new");
pw.document.open();
pw.document.write(makepage(src));
pw.document.close();
}
In the old method, the printme function knows what image should be printed: the same image that was clicked; when you change the trigger, you need to tell the function explicitly what image you want to print. That is why we are adding an id to the image and pass it to printme function. But if you only have one image on the page, or if a spacial relation exists (like the link always being the immediate next node after the image), then we can do it differently and need no id.
I don't know what your link looks like, but assuming it's just a plain anchor:
Change from:
<img src="fortune.jpg" onclick="printme(event)" />
To:
<img id="printableImage" src="fortune.jpg" onclick="printme(event)" />
<a href="javascript:void(0);" onclick="printme('printableImage')" />
Then alter the printme() function to retrieve the image src from the passed in image element id (jQuery makes this easy):
function printme(printableImageId)
{
var src = $('#' + printableImageId).attr('src');
// the rest of the logic...
}
You'll need to modify the printMe function a bit, doing this should fix it:
function printme(evt)
{
if (!evt) {
// Old IE
evt = window.event;
}
var anchor = evt.target;
if (!anchor) {
// Old IE
anchor = window.event.srcElement;
}
src = anchor.href;
link = "about:blank";
var pw = window.open(link, "_new");
pw.document.open();
pw.document.write(makepage(src));
pw.document.close();
return false;
}
And then on your actual anchor you would do the following:
Print

Categories