change to next image automatically - javascript

I have the following code used for displaying several images changed on hover, but i also would like to add a feature that changes the image automatically if i dont do it manually.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title><br />
</head>
<body>
<p>
<script type="text/javascript" language="javascript">
function changeImage(img){
document.getElementById('bigImage').src=img;
}
</script>
<img src="../Pictures/lightcircle.png" alt="" width="284" height="156" id="bigImage"
/>
<p> </p>
<div>
<p>
<img src="../Pictures/lightcircle2.png" height="79" width="78"
onmouseover="changeImage('../Pictures/lightcircle2.png')"/>
</p>
<p><img src="../Pictures/lightcircle.png" alt="" width="120" height="100"
onmouseover="changeImage('../Pictures/lightcircle.png')"/></p>
<p><img src="../Pictures/lightcircle2.png" alt="" width="78" height="79"
onmouseover="changeImage('../Pictures/lightcircle2.png')"/></p>
<p> </p>
</br>
</div>
</body>
</html>
What i want to do is automatically change the images displayed using javascript preferrably. How can i do that?

Use setInterval to run a function that changes the image src.
var x = 0;
var images = new Array("../Pictures/lightcircle2.png","../Pictures/lightcircle.png");
var i = setInterval(auto, 3000);
function auto()
{
x++;
if (x == images.length)
x=0;
document.getElementById('bigImage').src=images[x];
}

This should help you:
http://www.switchonthecode.com/tutorials/javascript-tutorial-using-setinterval-and-settimeout

Sounds like you want a carousel. If so, try this.
Add this to your JavaScript
// The list of images you want to cycle through
var imageRotation = [
'../Pictures/lightcircle.png',
'../Pictures/lightcircle2.png'
];
// The current image being displayed
var currentImage = 0;
// A variable to hold the timer
var t;
// Call this to automatically start rotation. Currently set for a 5 sec rotation
function startCarousel(){
t=setInterval(changeCarousel,5000);
}
// Moves to the next picture
function changeCarousel(){
// Change to the next image
currentImage++;
// If there isn't a next image, go back to the start
if (currentImage == imageRotation.length) currentImage = 0;
// Change the image
document.getElementById('bigImage').src=imageRotation[currentImage];
}
Then modify your function to
function changeImage(img){
// Stops the rotation
clearInterval(t);
// Assigns currentImage to the image they selected
currentImage = imageRotation.indexOf(img);
// Swap the image
document.getElementById('bigImage').src=imageRotation[currentImage];
// Start the rotation again in 10 sec
setTimeout(startCarousel, 10000);
}

Related

I cannot add images to the canvas of my thumbnail image gallery

I'm new to html and javascript. I am trying to add images to a canvas when clicked on by calling the image from the image gallery. I'm using the onclick method to my script and isn't working thus I am struggling. I've added my code below. Thank you for your help! The assignment ask...
Implement the imgOnClick(elmt) function so that it paints (to the canvas' drawImage() method) the image given by elmt. elmt will be an tag object. The canvas has the id imgresult.
In the document ready function, have each of the thumbnail images set their click event to the imgOnClick() function. I recommend you test this for one image before implementing it for the remaining images. Make sure you scale the image to a usable size.
<pre> <code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel=stylesheet type="text/css" href="memeory.css">
<title>Meme-ory :: Javascript Meme Generator</title>
<script type="application/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$( document ).ready(function() {
$('.thumbnail').click(imgOnClick('img'){
});
});
function imgOnClick('img') {
var canvas = document.getElementById("imgresult");
var ctx = canvas.getContext("2d");
var img = document.getElementById("closeenough");
ctx.drawImage(img, 10, 10);
};
};
function buttonOnClick() {
};
</script>
</head>
<body>
<header>
<h1>Meme-ory: Raging on in the Moonlight!</h1>
</header>
<main>
<div id="controls">
<form>
<label for="toptext">Top Text:</label>
<input id="toptext" type="text">
<label for="bottomtext">Bottom Text:</label>
<input id="bottomtext" type="text">
<input id="createMemeButton" type="button" value="Give me Meme!">
</form>
</div>
<div id="imagegallery">
<img class="thumbnail" id="closeenough" src="closeenough.png" alt="close enough">
<img class="thumbnail" id="cutenessoverload" src="cutenessoverload.png" alt="cuteness overload">
<img class="thumbnail" id="deskflip" src="deskflip.png" alt="deskflip">
<img class="thumbnail" id="lol" src="lol.png" alt="LOL">
<img class="thumbnail" id="trollface" src="trollface.png" alt="troll face">
</div>
<div id="memeresult">
<canvas id="imgresult">
</canvas>
</div>
</main>
</body>
</html>
If you try to select an element in a page, you can only do so when it has been created. You cannot select it BEFORE its existence. In this case you try to select a canvas and an image in the HEAD of you page, but these elements are only defined later on in your body.
There are two simple fixes:
Either you move your script code to the end of the page (just before </body>), or you include the code in the $( document ).ready(function() { block, like this:
$(document).ready(function() {
window.onclick = function imgOnClick(e) {
var canvas = document.getElementById("imgresult");
var ctx = canvas.getContext("2d");
var img = document.getElementById("closeenough");
ctx.drawImage(img, 0, 0);
};
});
Both ways ensure that you try to select the elements when they have been created.

RunningPuppy Animated Gif

I am stuck on my homework project. I am supposed to create a JavaScript program that shows an animated puppy running. I must use caching to start the animation as soon as the images finish loading and 1 of the following: getElementsByName(), getElementById(), or getElementsByTagName(). Here's what I have so far but when I run it in Firefox all I see is a flashing box that says "image of a puppy"
<!DOCTYPE HTML>
<html>
<head>
<title>Running Puppy</title>
<meta http-equiv="content-type" content="text/html;
charset=utf-8" />
<script type="text/javascript">
/* <![CDATA[ */
var puppy = new Array(6);
var curPuppy = 0
for (var imagesLoaded=0; imagesLoaded < 6;
++imagesLoaded) {
puppy[imagesLoaded] = new Image();
puppy[imagesLoaded].src
= "images/puppy" + imagesLoaded + ".gif";
}
function run(){
if (curPuppy == 5)
curPuppy = 0;
else
++curPuppy;
document.getElementById("puppyImage").src = puppy[curPuppy].src;
}
/*]]> */
</script>
</head>
<body onload="setInterval('run()', 150)">
<img src="images/puppy0.gif" id="puppyImage" width="263" height="175" alt="Image of a puppy." />
<script type="text/javascript">
/* <![CDATA[ */
document.write("<h1 id='mainHeading'></h1>");
document.getElementById("mainHeading").innerHTML = document.getElementsByTagName("title")[0].innerHTML;
/*]]> */
</script>
</body>
</html>

jquery preloaded imgages with rollovers

So I am doing something very basic that can be done with CSS but I want to do it with jQuery to get familiar with the library.
I am trying to create a rollover image gallery. Where when you put the mouse over the image it will be swapped with a slightly edited version of it.
Here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery</title>
<script src="jquery-1.9.1.js"></script>
<style>
</style>
</head>
<body>
<div id="gallery">
<img src="images/one_s.jpg" />
<img src="images/two_s.jpg" />
<img src="images/three_s.jpg" />
<img src="images/four_s.jpg" />
<img src="images/five_s.jpg" />
<img src="images/six_s.jpg" />
</div>
<script>
$(document).ready(function(){
var alternate = ['images/one_s_edited.jpg',
'images/two_s_edited.jpg',
'images/three_s_edited.jpg',
'images/four_s_edited.jpg',
'images/five_s_edited.jpg',
'images/six_s_edited.jpg'];
var $selection = $("#gallery img");
for(var i = 0; i < alternate.length; i++)
{
var imgObject = new Image();
var downloadedImg = imgObject.src = alternate[i];
console.log(downloadedImg);
var originalSrc = $selection.eq(i).attr("src");
console.log(originalSrc + "\n");
$selection.eq(i).hover(
function(){
$(this).attr("src", downloadedImg);
},
function(){
$(this).attr("src", originalSrc);
}
);//End hover
}//End loop
});//End ready
</script>
</body>
</html>
Here is a link to the final result: link
As you can see it rolls over but not as planned. It ends up with the last rollover-image and doesn't change back to the original nor does it show the appropriate rollover image that corresponds with it.
Any simple suggestions without using regular expressions?
The problem is the wrong usage of a closure variable in a loop.
But the solution can be simplified to
$(document).ready(function () {
var $selection = $("#gallery img");
$selection.hover(function () {
this.src = this.src.replace('.jpg', '_edited.jpg')
}, function () {
this.src = this.src.replace('_edited.jpg', '.jpg')
})
}); //End ready

html javascript

I have a problem with javascript.
I need to add onclick listener for all img tags in my page, so click on an image should call imageClicked and pass element to function. but this code all time pass img src="../images/3.jpg" to function.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="style.css" type="text/css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sample Page</title>
</head>
<body onload="start()">
<script type="text/javascript">
function start(){
var images = document.getElementsByTagName("img");
for ( var i = 0; i < images.length; i++) {
var image=images[i];
image.addEventListener('click', function(){
imageClicked(image);
});
}
}
function imageClicked(image){
alert(image.src)
}
</script>
<div id="main">
<div id="center">
<button>نمایش اسلایدی</button>
</div>
<div id="gallery">
<div id="img1" class="image">
<img src="../images/1.jpg"></img>
<div id="title">
<label>عکس</label>
</div>
</div>
<div id="img2" class="image">
<img src="../images/2.jpg"></img>
<div id="title">
<label>عکس</label>
</div>
</div>
<div id="img" class="image">
<img src="../images/3.jpg"></img>
<div id="title">
<label>عکس</label>
</div>
</div>
</div>
</div>
That is because of the scope. Everytime you loop the image value is set again. And so it will always pass the last image in the loop.
You can do 2 thing. Use the this like below. Or create an anonymouse function.
function start(){
var images = document.getElementsByTagName("img");
for ( var i = 0; i < images.length; i++) {
images[i].addEventListener('click', function(){
imageClicked(this);
});
}
}
// Or even better
function start(){
var images = document.getElementsByTagName("img");
for ( var i = 0; i < images.length; i++) {
images[i].addEventListener('click', imageClicked);
}
}
function imageClicked(){
alert(this.src); // this refers to the image
}
Anonymouse function:
function start(){
var images = document.getElementsByTagName("img");
for ( var i = 0; i < images.length; i++) {
(function(image){
image.addEventListener('click', function(){
imageClicked(image); // Use the element clicked object (this)
});
})(images[i]);
}
}
What you want is something like this:
function start(){
var images = document.getElementsByTagName("img");
for ( var i = 0; i < images.length; i++) {
images[i].addEventListener('click', function(){
imageClicked(this);
});
}
}
function imageClicked(image){
alert(image.src)
}
In the code you wrote, you copied the image element and then assigned an eventListener to the copy of the object. Because this copy was over-written multiple times, imageClicked was referred to by the only one that wasn't over-written, the last image. The this is to refer to the actual image element in the callback function.

call on function when all images are clicken on

I want to call a function that opens a new link. I want to do this after all my images have been clicked on. How can i achieve this?
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="windows-1252">
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"> </script>
<![endif]-->
<title>Date med mig - version b
</title>
<script type="text/javascript">
function newWindow()
{
window.location = window.location = "http://www.tv3.se/datemedmig"
}
</script>
</head>
<body>
<h1>Del 2: Date med mig</h1>
<img src="1_c.jpg" id="image1" onclick="this.src='1_o.jpg';" alt="image" />
<img src="2_c.jpg" id="image1" onclick="this.src='2_o.jpg';" alt="image" />
<img src="3_c.jpg" id="image1" onclick="this.src='3_o.jpg';" alt="image" />
<img src="4_c.jpg" id="image1" onclick="this.src='4_o.jpg';" alt="image" />
</body>
</html>
If you are trying to just load a new window as soon as any image is clicked, I think the way that #runfaj said to do it is probably the best, It is my understanding that you want to do it only after ALL images have been clicked on?
If this is the case, here's one option (which is probably not the most efficient)
//Assuming there are 4 images
var hasBeenClicked = [false,false,false,false]
//To be called when each image is clicked
function imageClicked(whichImage){
this.src = "'"+whichImage+"_o.jpg'"
//set this position in the array equal to true
hasBeenClicked[whichImage] = true
// if the array is completely true (every image has been clicked)
// call the newWindow function
if(hasBeenClicked == [true,true,true,true]){
newWindow();
}
}
Then when you create an image:
<img src="1_c.jpg" id="image1" onclick="imageClicked(1);" alt="image" />
you could do it three ways:
jquery:
$('img').click(newWindow);
inline:
<img src=..... onclick="newWindow()" />
regular javascript:
get all the tags with:
var imgs = document.getElementByTagName('img');
then add an event listener to each one (google it for lots of different examples)
Have an onclick function that triggers for each image which sets a new attribute on the image tag. Then run a loop over all images to check that they all have the tag. If so, open new windows. For example:
$('img').click(function() {
$(this).data('was-clicked', true);
var all_clicked = true;
$('img').each(function() {
if($(this).data('was-clicked') != true) {
all_clicked = false;
break;
}
});
if(all_clicked == true) newWindow();
});
Note, this code is not tested and may have syntax/semantic errors. Also, you may not really want the user to click ALL image tags (e.g. banners, backgrounds, etc), so you should modify the jquery selectors to filter only the 'img' tags you're interested in, e.g. $('#my-gallery img')...

Categories

Resources