jquery preloaded imgages with rollovers - javascript

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

Related

Adding another image using Javascript

Please find the code and advise.
I am trying to add an another image ('correct10.png') onClick Event of displayed image i.e 'Van.png'. But nothing happend, so please suggest.
Here the html :
<!DOCTYPE html >
<html lang="en">
<head>
<title>Adding Another Image onClick</title>
<script>
function doImgSwap()
{
document.getElementById('newImg').addEventListener('click', function(e){
var img = document.createElement('img');
img.setAttribute('src','correct10.png');
e.target.appendChild(img);
});
}
</script>
</head>
<body>
<p><img src="van.png"></p>
</body>
</html>
Your doImgSwap method creates an event handler, it does not actually swap the image.
Should be:
function doImgSwap(el){
var img = document.createElement('img');
img.setAttribute('src','correct10.png');
el.appendChild(img);
}
And you'll have to pass in the element in the onClick attribute, like this
onClick="doImgSwap(this)"
here's a working jsfiddle of your code
Your code should be
<!DOCTYPE html>
<html lang="en">
<head>
<title>Adding Another Image onClick</title>
<script>
window.onload = function() {
document.getElementById('newImg').addEventListener('click', function(e) {
var img = document.createElement('img');
img.setAttribute('src', 'correct10.png');
this.appendChild(img);
});
}
</script>
</head>
<body>
<p>
<a href="#" id="newImg">
<img src="van.png"/>
</a>
</p>
</body>
</html>
start by putting the js file under your html or use window.onload function to be sure
<!DOCTYPE html >
<html lang="en">
<head>
<title>Adding Another Image onClick</title>
</head>
<body>
<p><img src="van.png"></p>
<script>
function doImgSwap()
{
document.getElementById('newImg').addEventListener('click', function(e){
var img = document.createElement('img');
img.setAttribute('src','correct10.png');
e.target.appendChild(img);
});
}
</script>
</body>
</html>

Add Class not working even in document ready

the add class is not working even if it is in document ready. I tried both with document ready and without it. it is not working but alert is working.
var $jbanner = jQuery.noConflict(true);
if ($jbanner(window).width() < 1200) {
alert("Less than 1200");
$jbanner("#wad").addClass("hide");
}
other code
var $jbanner = jQuery.noConflict(true);
$jbanner(document).ready(function () {
if ($jbanner(window).width() < 1200) {
alert("Less than 1200");
$jbanner("#wad").addClass("hide");
}
})
With document ready function even the alert box is not working. is it conflicting with other jquerys in the page.
#wad is an image
<img id="wad" src="images/banner.jpg"/>
thanks
ok this should be pretty easy, but not working for me. I just pasted what i am trying to do in a separate html file. but still not working, any help is appreciated.
<!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>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.js"></script>
<script type="text/javascript">
var $jbanner = jQuery.noConflict(true);
if ($jbanner(window).width() < 1200) {
alert("Less than 1200");
$jbanner("#wad").addClass("hide");
}
else {
alert("greater than 1200");
$jbanner("#wad").addClass("show");
}
</script>
<style type="text/css">
.hide{display:none;}
.show{display:block;}
</style>
</head>
<body><div>
<div id="wallpaperad">
<a href="http://www.yaho.com" target="_blank" rel="nofollow">
<img src="http://www.placehold.it/160x160" alt="banners" id="wad" /> </a>
</div>
</div>
</body>
</html>
I am just trying to create a floating banner ad. that hides for smaller screen sizes.
Try to without jbanner.
$("#wad").addClass("hide");

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>

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.

How to load image asynchronously using jquery while animating pictures as screenshot

I'm trying to load an image asynchronously using jquery javascript framework. The loaded image should be faded in when it's completely downloaded to local page. By now I'm able to asynchronously load an image and fade it in after a constant time not when its completely downloaded. This produces some graphical errors while fading if image is tall and download takes a moment of time because of image size. Also the memory allocated by the browser is increasing step by step when a image is loaded asynchronously. Even the same images shown before allocates new memory.
How can I load an image asynchronously and do some fading when it's completely downloaded. And how do I have to load the image to get no memory leak in my browser.
<!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 charset="utf-8">
<title>jQuery demo</title>
</head>
<body>
<script src="jquery-1.8.0.min.js"></script>
<script src="jquery.timer.js"></script>
//<script src="jquery.center.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<div class="hide">
<img id="bild" height=100% src="logo.jpg" alt="Logo" />
</div>
<script>
var timer = $.timer(function()
{
var img = $('#bild').attr('src','http://localhost/test.php?'+(new Date()).getTime()).load(function()
{
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
$('#bild').attr('src','logo.jpg'); //Show logo in error case
} else {
$("#div.hide").append(img);
}
}).stop(true,true).fadeIn(1000).delay(3000).fadeOut(1000);
});
$("#bild").error(function()
{
$('#bild').attr('src','logo.jpg');
});
timer.set({ time : 5000, autostart : true });
</script>
</body>
</html>
Try this:
if($('#bild').prop('complete')) // if image is already in cache
{
// your code
$(this).fadeIn(1000).delay(3000).fadeOut(1000);
}
else{
$('#bild').load(function(){ // works when image is loaded and not present in cache
// your code
$(this).fadeIn(1000).delay(3000).fadeOut(1000);
});
}
thanks for your code examples. After some tries with it and some further help from a friend we get it working. 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 charset="utf-8">
<title>jQuery demo</title>
</head>
<body>
<script src="jquery-1.8.0.min.js"></script>
<script src="jquery.timer.js"></script>
//<script src="jquery.center.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<div id="imageWrapper" class="hide">
<img id="bild1" style="height: 100%;" src="logo.jpg" alt="Logo" />
<img id="bild2" style="height: 100%; display: none;" src="logo.jpg" alt="Logo" />
</div>
<script>
setImage($('#bild2'));
var timer = $.timer(function()
{
var visible = $('#imageWrapper img:visible');
var hidden = $('#imageWrapper img:hidden');
if (!hidden[0].complete || typeof hidden[0].naturalWidth == "undefined" || hidden[0].naturalWidth == 0)
hidden.attr('src','logo.jpg'); //Show logo in error case
if(hidden.attr('src')!= visible.attr('src'))
{
visible.fadeOut(1000, function() {
setImage(visible);
hidden.fadeIn(1000);
});
}
else
setImage(hidden); //don't fade if current and next picture are the same (e.g. error pic -> error pic), but try to set new image
});
$("#imageWrapper img").error(function()
{
$(this).attr('src','logo.jpg');
});
timer.set({ time : 5000, autostart : true });
function setImage(img)
{
img.attr('src','http://localhost/test.php?'+(new Date()).getTime());
}
</script>
</body>
</html>
www.farinspace.com/jquery-image-preload-plugin/
That jQuery plugin will do what you're looking for. You have callback functions for each image load event, then another callback for when all images are done loading.
$imgs.imgpreload({
each: function() {
// an image loaded, you could fade in each one
},
all: function(){
// all images loaded, you could do something else here
}
});
alternatively you can preload the images so they start downloading before the browser reaches them in the DOM.

Categories

Resources