Changing hover image after repeated hovers using Jquery - javascript

I am trying to change the src attribute in an img tag in html using jquery, I want scr attribute to change differently depending on the number of times the user has hovered over the img element.
My html is set up as follows:
<img id="element" src="img1.png">
My js/jQuery is set up as follows:
var count = 0;
if(count == 0){
$("#element").hover(function(){
count++;
$("#element").attr("src","img2.png");
}, function(){
$("#element").attr("src","img1.png");
});
} else if(count>=1){
$("#element").hover(function(){
count++;
$("#element").attr("src","img3.png");
}, function(){
$("#element").attr("src","img1.png");
});
}
The hover function on its own works fine, and hovering in and out will switch between two images. However, my goal is to make it switch to img2 in the first hover, and then img3 at the second hover, and thereafter. My hover function seems to work fine if I want it to hover between img1 and img2 or img 1 and img3, that is when I remove if statement and count variable.
If someone could help identify my problem please.

You need to do the counter check within the hover handler
var counter = 0;
$("#element").hover(function() {
$(this).attr("src", ++counter > 1 ? '//placehold.it/64X64/00ff00' : '//placehold.it/64X64/0000ff');
}, function() {
$(this).attr("src", "//placehold.it/64X64/ff0000");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="element" src="//placehold.it/64X64/ff0000">
In your code the value of counter is checked only once on page load where the value of counter is always 0

From what you've posted, if(count == 0) occurs in your setup code. None of your hover event handlers touch the value of count, so once the handlers are set (either to 1 and 2 or 1 and 3), they will never be changed. And since count is always zero when the handlers are added, you always get the first pair.
Instead, you should switch between the two images inside of your handler function, not in the code that assigns the handler.

Try creating array of strings containing img src , utilizing Array.prototype.reverse() to toggle images
var imgs = ["img2.png", "img3.png"];
$("#element").hover(function() {
$(this).attr("src", imgs[0]);
imgs.reverse()
}, function() {
$(this).attr("src", "img1.png");
});
var imgs = ["http://lorempixel.com/100/100/sports", "http://lorempixel.com/100/100/cats"];
$("#element").hover(function() {
$(this).attr("src", imgs[0]);
imgs.reverse()
}, function() {
$(this).attr("src", "http://lorempixel.com/100/100/nature");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img id="element" width="100px" src="http://lorempixel.com/100/100/nature" />

What about some simplicity?
var counter = 1;
$("#element").hover(function () {
counter = (counter===3) ? 1 : (counter+1);
$(this).attr("src", 'img'+counter+'.png');
}

Not sure if this will work just something I looked up but you can try it.
Just add more variables to it.
jQuery(document).ready(function($) {
//rollover swap images with rel
var img_src = "";
var new_src = "";
$(".rollover").hover(function(){
//mouseover
img_src = $(this).attr('src'); //grab original image
new_src = $(this).attr('rel'); //grab rollover image
$(this).attr('src', new_src); //swap images
$(this).attr('rel', img_src); //swap images
},
function(){
//mouse out
$(this).attr('src', img_src); //swap images
$(this).attr('rel', new_src); //swap images
});

How about this?
$(document).ready(function(){
var count = 1;
$("#element").hover(function() {
count++;
$(this).attr("src","img"+count+".png");
if(count == 3){
//Reset the count
count = 0;
}
}, function() {
$(this).attr("src", "img1.png");
});
});

Related

play/stop gif on click using javascript

I want a gif to play when clicked, and to stop when clicked again. I'm following this method: http://www.hongkiat.com/blog/on-click-animated-gif/
So far, I have:
HTML
<figure>
<img src="test.png" alt="Static Image" data-alt="test.gif"/>
</figure>
<script src="playGif.js" type="text/javascript"></script>
playGif.js
(function($) {
// retrieve gif
var getGif = function() {
var gif = [];
$('img').each(function() {
var data = $(this).data('alt');
gif.push(data);
});
return gif;
}
var gif = getGif();
// pre-load gif
var image = [];
$.each(gif, function(index) {
image[index] = new Image();
image[index].src = gif[index];
});
// swap on click
$('figure').on('click', function() {
var $this = $(this),
$index = $this.index(),
$img = $this.children('img'),
$imgSrc = $img.attr('src'),
$imgAlt = $img.attr('data-alt'),
$imgExt = $imgAlt.split('.');
if($imgExt[1] === 'gif') {
$img.attr('src', $img.data('alt')).attr('data-alt', $imgSrc);
} else {
$img.attr('src', $imgAlt).attr('data-alt', $img.data('alt'));
}
});
})(jQuery);
Instead of swapping the content of src and data-alt, this only puts data-alt into src, and data-alt remains the same.
The gif does play on click, but if clicked again it reloads the gif instead of reverting to the png (at least in Chrome and Firefox. IE just does nothing on further clicks).
So here is the finished jsfiddle: https://jsfiddle.net/2060cm1c/
It is a simple variable swapping problem:
a=1;b=2;
a=b;// now a=2
b=a;// a=2, b=a=2
To solve it, you need a temporary variable:
a=1;b=2;
temp=a;a=b;
b=temp;
Now solve the OP's problem:
var temp=$img.attr('src');
$img.attr('src', $imgAlt).attr('data-alt', temp);
So, the problem is as easy as swapping 2 variables. You don't need the if to check the extension.

100% fully show image before fading in

I have 2 images. My intention is when the image finished display, and finished fade in, I will load some function.
My question
How do I make sure my image is fully loaded and displayed on screen?
I ask because sometimes, when the image is still loading (like only half the image is showing), it will fade in somehow, I need make sure it shows the full image before fading in.
FIDDLE
var temp = "";
var displaythumbnailbox = $(".area1");
var lis = $(".area1 img");
//hide the image , in order to use fadein
lis.hide();
lis.each(function(i) {
$(this).fadeIn('fast', function() {
console.log("finish load all image");
if (i == lis.length - 1) {
//getting last image display.
alert("finish display the last image");
//going to put some function here.
}
});
});
You can substitute css display:none for .hide(), .ready() , .promise()
css
.area1 img {
display:none;
}
javascript
$(document).ready(function() {
var temp = "";
var displaythumbnailbox = $(".area1");
var lis = $(".area1 img") //.hide()
.each(function(i) {
$(this).fadeIn("fast", function() {
console.log("finish load all image");
});
});
lis.promise().then(function() {
alert("finish display the last image");
})
})
jsfiddle https://jsfiddle.net/88ft369z/3/
If you want to display images in sequence you can substitute i multiplied by a duration, e.g., i * 250 at .each() for "fast" jsfiddle https://jsfiddle.net/88ft369z/4/
You can check if the element is loaded using .load().
var lis = $(".area1 img");
lis.load(function(){
lis.hide();
lis.each(function(i) {
$(this).fadeIn('fast', function(){
console.log("finish load all image");
if(i == lis.length -1)
{
//getting last image display.
alert("finish display the last image");
//going to put some function here.
}
});
});

changing part of src name with jquery, keeps repeating when window resized

I have code written to find the src of all images inside a particular div and change the src name when the window is less than 900 wide. It works fine upon page refresh, but when I resize the window it continuously runs the code and I get this error
GET
file://macintosh%20hd/Users/jessicamele/Desktop/tom%20mendicino/images/boys3_small_small_small_small.jpg
net::ERR_FILE_NOT_FOUND
It just keeps adding the "_small" over and over again. Here is my code:
<div class="threePicsBoys group">
<img src="images/boys3.jpg" alt="street signs" class="boysPics1">
<img src="images/boys2.jpg" alt="city house" class="boysPics2">
<img src="images/boys1.jpg" alt="2 boys" class="boysPics1">
<img src="images/boys4.jpg" alt="philly signs" class="boysPics2">
<img src="images/boys5.jpg" alt="religious statue" class="boysPics1">
</div>
$(function() {
if (windowWidth <= 900) {
var img = $(".threePicsBoys.group").find("img").map(function() {
var src = $(this).attr("src");
var newName = src.replace(".jpg","_small.jpg");
$(this).attr("src",newName);
});
}
});
}
I could really use some help.
This script will check if the window is so thin that it has to change the src, but will also revert the changes when it have become wider than 900.
I slightly changed the mechanics to make it work. windowWidth, for example, wasn't a declared variable, and the rest didn't seem to do that much either.
var thinWindow = false;
$(window).on('load resize', function(){
if($(window).width() <= 900){
if(!thinWindow){
$('.threePicsBoys.group img').each(function(){
var src = $(this).attr("src");
var newSrc = src.replace(".jpg","_small.jpg");
$(this).attr("src", newSrc);
})
thinWindow = true
}
}else{
if(thinWindow){
$('.threePicsBoys.group img').each(function(){
var src = $(this).attr("src");
var newSrc = src.replace("_small.jpg",".jpg");
$(this).attr("src", newSrc);
})
thinWindow = false
}
}
})
Hope this helps
This code will loop forever when window is less than 900 width. If you wish to you only run on window change width you must add the correct event binding
$(window).resize(function() {
if (windowWidth <= 900)
{
var img = $(".threePicsBoys.group").find("img")
var src = img.attr("src");
if (!(src.indexOf("_small.jpg") > -1))
{
var newName = src.replace(".jpg","_small.jpg");
img.attr("src",newName);
}
}
});

fading image at random

I wonder if anyone can help or point me in the right direction.
I have a grid of images. What I'm hoping to do is grab all the images on the page and put them in an array(done). Then every 3 seconds I want to to randomly choose an image, fade it out and fade in another image from the same page.
can someone help me with this?
I've got a nice script I made once, it does use jquery though:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var curIndex = 0;
var src = ['imgs/derp.jpg', 'imgs/derp2.png'];
var fadeTimeInMilliseconds = 2000;
var waitTimeInMilliseconds = 5000;
$(document).ready(function(){
switchImageAndWait(true);
});
function switchImageAndWait(fadeOut2){
if(fadeOut2){
setTimeout(fadeOut, waitTimeInMilliseconds);
}else{
var index = Math.floor((Math.random()*src.length))
if(curIndex == index){
index++;
if(index >= src.length){
index-=2;
}
}
curIndex = index;
$("#swekker").attr("src", src[index]);
fadeIn();
}
}
function fadeOut(){
$("#swekker").fadeTo( fadeTimeInMilliseconds, 0 , function() { switchImageAndWait(false); });
}
function fadeIn(){
$("#swekker").fadeTo( fadeTimeInMilliseconds, 1 , function() { switchImageAndWait(true); });
}
</script>
It's a jquery script script that continuously fades in, waits and fades out again.
To use this script simply add it to an image:
<img width="602" height="400" src="imgs/derp.jpg" id="swekker"/>

JavaScript to change images

I have set of images named as img1, img2, img3, img4,......., imgx. So, I want to code a JavaScript to display an image img1 at document.onload() and on first click image to be changed to img2 next on second click the image to be changed at img3 and then same to the next image on every NEXT button click. In this manner I need even PREVIOUS button to go back to the previously viewed images.
How to implement this?
var currentImage = 1;
window.onload = function() {
showImage();
};
document.getElementById("next").onclick = function() {
currentImage++;
showImage();
}
function showImage() {
document.getElementById("image").src = "img" + currentImage + ".jpg";
}
These are the basics and should help you get started. If you need help implementing the rest, ask us what you want to do specificially and what you tried. Hint, you'll need to handle the case where there is no "next" image to show. Do you want it to come back to the beggining or just not work?
<script type="text/javascript">
var images = new Array("img/image1.jpg", "img/image2.jpg", "img/image3.jpg");
var cur_image = 0;
function goNextImage() {
var img = document.getElementById('image');
cur_image++;
if (cur_image == images.length) {
cur_image = 0;
}
img.src = images[cur_image];
}
</script>
<img src="img/image1.jpg" id="image" onclick="goNextImage()" />

Categories