Change image source on mouseover then get the image back on mouseout - javascript

<img src="img/image1.png" id="mainimage">
<p>Dog</p>
<p>Cat</p>
I am trying to use JavaScript/jQuery so that whenever a user places their mouse over any of the links with the id's pet1 & pet2 it will change the image src of the image with the id of mainimage.
var img = document.getElementById('swap');
document.getElementById('pet1').onmouseover = function(){
// manipulate the image source here.
img.src = img.src.replace(/\.jpg/, '-on.jpg');
}
The above JavaScript is a script I found here that seems to have the functionality I am looking for. The only problem is that whenever my mouse is over the link it does not display the image I want. Ok, the question I am looking for is how can I make the image with the source (img/pet1.jpg) appear?
Any help will be appreciated!

Try this more simply
$(function() {
$("#pet1")
.mouseover(function() {
var src = 'first image path';
$("#mainimage").attr("src", src);
})
.mouseout(function() {
var src2 ='Default image path';
$(this).attr("src", src2;
});
});
Similllar for second image and for shortening even this you can give a class to every link you want and then by using $(element).each() function and "data" attribute of html5 you can manage it in more cool way

This should get you started.
For all links at once we set a mouseover handler (which takes the ID of the link, turns it into a path to the image, and displays it) and a mouseout handler (which reverts the image's src to its original image).
$(document).ready(function() {
// To start with, get a reference to the image and its original src
var $mainImage = $('#mainimage'),
originalImageSrc = $mainImage.attr('src');
// Then add mouseover and mouseout handlers to all the links
$('a')
.on('mouseover', function() {
var newImageSrc = 'img/' + $(this).attr('id') + '.jpg';
$mainImage.attr('src', newImageSrc);
})
.on('mouseout', function() {
$mainImage.attr('src', originalImageSrc);
});
});
You can see it working in this JSFiddle. So that you can see it working in the JSFiddle without real images, I've used a div's text rather than an img's src, but that's just for the demo.
Of course you could always adapt it (maybe you want to be more specific than all a tags, and maybe you don't always want to use the format img/<id>.jpg – in which case you could add a data-img-src attribute to all your links and use .data('imgSrc') instead of the .attr('id')).

Hopefully this is what you're looking for.
HTML:
<img src="http://placehold.it/300x150" id="theImage">
<p>Red</p>
<p>Blue</p>
JS:
$('.yourClass').hover(function() {
var newImg = $(this).data('img');
$('#theImage').attr('src',newImg)
}, function() {
$('#theImage').attr('src','http://placehold.it/300x150')
});
JSFiddle

Related

onload not working in <img> element

I don't understand why this function doesn't fire. I want to declare an image in HTML with a single onload function, which will automatically take care of the image's source and mouseover/out functions.
The HTML looks like this:
<img id="menuBtnNovo" onload="imgButton(this)"/>
and the JS function imgButton looks like this:
function imgButton(e){
window.alert("asdasdad");
e.src="images/def/" + e.Id + ".png";
e.onmouseover= function(){ *change image here*}
e.onmouseout= function(){ *change image back here*}
}
Now, not even the alert pops up, and I don't know why. I tried putting script in <head> and setting src to none src="" in the <img>. I'm using Firefox, but it doesn't work in Edge either.
Question is: how do I fire onload function on an image element?
Also, if you have any idea of your own way of implementing this behaviour of automatically loading certain images (that would actually be buttons/links), feel free to share it. I'm new to JS but not to programming.
As you might see, all images are in "images/def/..." and all images for when the mouse is over the img are in "images/mo/...".
I always try and let browser do image replacements, but if you have to use script, than you can do something like this on DOM ready, or window load event:
$('img[data-regular]').each(function(i) {
var thisImage = $(this);
var regular = thisImage.data('regular');
var hover = thisImage.data('hover');
thisImage.attr('src', regular);
/* Preload image for hover */
$('<img/>')[0].src = hover;
/* Set events */
thisImage.on('mouseenter', function(e) {
thisImage.attr('src', hover);
}).on('mouseleave', function(e) {
thisImage.attr('src', regular);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img data-regular="https://placehold.it/350x150" data-hover="https://placehold.it/450x200" />
Also on JSFiddle.

Pre-load Jquery hover images

Right now I am building a map of the US, and when you hover over any given state, I am replacing the image with an image of a different color.
My problem is that the way I am currently doing things, the image is being replaced and a new image loaded on hover.
I have the HTML laid out as:
<img class="state" id="alaska" src="img/united-states_Alaska.png" alt="alaska">
<img class="state" id="hawaii" src="img/united-states_hawaii.png" alt="hawaii">
And the jQuery I am using is:
$('.interactive-map img').each(function(e){
var src = $(this).attr('src');
$(this).hover(function(){
$(this).attr('src', src.replace('.png', '-hover.png'));
}, function(){
$(this).attr('src', src);
});
});
I am curious if there is another way to either preload the images with JavaScript, or make it so that there isn't a new request for image every time I hover. I would like to not have to change the HTML or CSS much and optimize it in JavaScript.
Add your images to the DOM on page load but in hidden state, then they get cached
$(function() {
var images = ['url/to/your/jpg1.jpg', 'ur/to/your/png2.png'];
var d = document.createElement("div");
d.style.display = 'none';
document.body.appendChild(d);
for (var i in images)
{
var img = document.createElement("img");
img.src = images[i];
d.appendChild(img);
}
});
Have two image tags and set the first image's display: block. Set the second image's display: none.
Then on hover you switch the them. It is as easy as that.
Use PreloadJS
Example:
var preload = new createjs.LoadQueue();
preload.addEventListener("fileload", handleFileComplete);
preload.loadFile('http://createjs.com/images/404/gBot-confused.jpg');
function handleFileComplete(event) {
document.body.appendChild(event.result);
}
Full Docs: here
Another interesting post using JS and AJAX: Preloading

Target slides by z-index and assign class

here is what I am trying to achieve. On this page http://livinginspace.staging.wpengine.com/ there are four sharing buttons. First three work perfectly fine, but the houzz works only for one image. What I am trying to achieve is to dynamicly change the button's href attribute depending on the current slide, so when you press it you are sharing the slide that was on the screen when you pressed the houzz button.
As I noticed, all you need to change inside the href of the button is the image url. Also, the only thing that changes (at least that I've noticed) is the z-index of the li element inside the slider div.
Here are my steps:
//first I am targeting the li with z-index 20
var currLi = $('li').filter(function() {
return $(this).css('z-index') == 20;
});
//then i target the url of the image inside that li
var imgUrl = $(currLi + '>div.slotholder>img').attr('src');
//finally I put the url into the houzz button
$('a.sb_network_button.houzz').attr("href", "http://www.houzz.com/imageClipperUpload?link=http%3A%2F%2Flivinginspace.staging.wpengine.com%2F&source=button&hzid=4036&imageUrl=" + imgUrl + "&title=Product+Title+as+it+will+be+seen+inside+Houzz&ref=http%3A%2F%2Flivinginspace.staging.wpengine.com%2F");
Altogether that is:
jQuery(document).ready(function($) {
var currLi = $('li').filter(function() {
return $(this).css('z-index') == 20;
});
var imgUrl = $(currLi + '>div.slotholder>img').attr('src');
$('a.sb_network_button.houzz').attr("href", "http://www.houzz.com/imageClipperUpload?link=http%3A%2F%2Flivinginspace.staging.wpengine.com%2F&source=button&hzid=4036&imageUrl=" + imgUrl + "&title=Product+Title+as+it+will+be+seen+inside+Houzz&ref=http%3A%2F%2Flivinginspace.staging.wpengine.com%2F");
});
I am pretty new to jquery, and I can't remember all the things I've tried but I have done everything I can and it still doesn't work. Also, I have noticed that when I put the code at the very end of the footer, it doesn't work at all (tried putting alerts, just to test), but when it's in the header or beginning of footer (before all other scripts) the alerts work, but I believe the problem might be that the actual li elements that I am trying to target are not yet created. Please help me with it, I've spent so many hours trying to figure this out.
Thanks a lot
To get the "li" with z-index of 20 you can do this, which will get the image URL inside of that "li":
var imgUrl;
$('li').each(function() {
if($(this).css('zIndex') == 20) {
imgUrl = $(this).find('img').attr('src');
}
});
-------------------------------------EDIT---------------------------------------------
I have made a JSFiddle that successfully gets an image src and then places it has the href on an a tag. See it here
The code is below (including the code above that I already had for finding the imgURL of the image with z-index of 20). Obviously, I am using two buttons in my example, but just for testing that the href is undefined initially, to set the href, then check it again.
$('#btn').click(function() {
//Get image with z-index = 20
$('li').each(function() {
if($(this).css('zIndex') == 20) {
imgUrl = $(this).find('img').attr('src');
}
});
$('.a').attr('href', imgUrl);
});
$('#btn2').click(function() {
alert($('.a').attr('href'));
});

Fading background images with jQuery/css?

I have the following script (from here) that loads up an image and sets it as the background. It works fine, but what would I need to change to add more than one photo so it can be a slideshow?
jQuery:
$(document).ready(function(){
$.fn.smartBackgroundImage = function(url){
var t = this;
//create an img so the browser will download the image:
$('<img />')
.attr('src', url)
.load(function(){ //attach onload to set background-image
t.each(function(){
$(this).css('backgroundImage', 'url('+url+')' );
});
});
return this;
}
$('body').smartBackgroundImage('/static/images/temp-bg.jpg');
});
Thank you!
incorporate your images in html with <li> tags, and format them with jquery. so its easier to change them later on.

Creating button rollovers with jQuery

I'm trying to make a function that I can use globally to create rollover states for images. Basically, I want to be able to add a class to an image, and then when you rollover it, jquery will use the same image name, and same extension, but add "-over" to the file name. (I'll have an image with the rollover state named the same as the non rolled over state except with the -over on it. I came up with this, but it's not working. Am I doing something wrong or does anyone know of a better way to do it?
$('.btn').hover(function(){
$(this).attr("src").split(".jpg").join("Over.jpg"));
});
image:
<img src="/static/images/overlay-close-button.jpg" alt="Close" title="Close" id="our-staff-overlay-close" class="btn"/>
Thanks!
EDIT: Is there any way to make it non specific to the file time, where it can figure out any file type rather than just jpgs?
I'm using:
$('.btn').hover(function(){
this.src = this.src.split(".jpg").join("Over.jpg");
}, function() {
this.src = this.src.split("Over.jpg").join(".jpg");
});
and it's working great
EDIT 2: Can I also add an active state (when the button is being clicked)?
The splitting and joining should work as intended, you just need to set that back to the src attribute of the img:
$('.btn').hover(function() {
var src = $(this).attr("src");
src = src.split('.jpg').join('-over.jpg');
$(this).attr("src", src);
});
Also, if you want it to work with any extension, you could use a regular expression like this:
$('.btn').hover(function() {
var src = $(this).attr("src");
src = src.replace(/(.*)\.(png|gif|jpg|jpeg)$/, "$1-over.$2");
$(this).attr("src", src);
});
The regular expression matches anything that ends with a period followed by one of png, gif, jpg, or jpeg, and replaces it with the first part (the path + filename), the string "-over", a period, and the original extension.
You can replace it back to the original state by removing the -over from the source:
$('.btn').hover(function() {
var src = $(this).attr("src");
src = src.replace(/(.*)\.(png|gif|jpg|jpeg)$/, "$1-over.$2");
$(this).attr("src", src);
}, function() {
var src = $(this).attr("src");
src = src.replace(/(.*)-over\.(png|gif|jpg|jpeg)$/, "$1.$2");
$(this).attr("src", src);
});
The jQuery().hover event accepts two functions, the first one is called when you start the hover, the second one is called when you exit the hover.
You're just not doing anything with the result. In this case you want to set the src (which can be done a few ways), here's the most efficient example (without changing your .split().join() method):
$('.btn').hover(function(){
this.src = this.src.split(".jpg").join("Over.jpg");
}, function() {
this.src = this.src.split("Over.jpg").join(".jpg");
});
$('.btn').hover(function(){
$(this).attr("src", this.src.split(".jpg")[0] + "-over.jpg");
}, function() {
$(this).attr("src", this.src.split("-over.jpg")[0] + ".jpg");
})
You may want to consider achieving your rollover effect using pure CSS. It's really not necessary to involve script in something as trivial as a image rollover. Plus, a pure CSS approach will still work for the paranoids out there who browse with script turned off.
Use the :hover and :active pseudoclasses and take advantage of CSS sprites.
The downside here is that this method is harder to make generally applicable because you need to know the size of your images before-hand.

Categories

Resources