Reputation: 384
I am trying to make a jQuery image viewing gallery so you hover over the image and it becomes the background the gal (gallery) div.
$(document).ready(function(){
$("#img1").hover(function(){
var img1 = document.getElementById("gal");
gal.style.background="url(images/img1.png), black";
});
$("#img1").mouseout(function(){
gal.style.background="none";
});
});
$(document).ready(function(){
$("#img2").hover(function(){
var img2 = document.getElementById("gal");
gal.style.background="url(images/img2.png), black";
});
$( "#img2" ).mouseout(function(){
gal.style.background="none";
});
});
The html code
<section>
<h1> Images</h1>
<h3> Photos </h3>
<div id="gal">
</div>
<img id="img" src="images/img1.png" width="100px" height="100px"/>
<img id="img" src="images/img2.png" width="100px" height="100px"/>
</section>
This is my code and it works perfectly fine but using this code I am required to input each div individually.
Is there a way so when you hover over an image it knows what image that is and it makes the div background equal that? Thank you for your help.
P.S. I am quite new to JavaScript.
Upvotes: 5
Views: 190
Reputation: 2822
Try this:
$(document).ready(function(){
var gal = $("#gal"); //Avoid repeated traverse
$("img").hover(function(){
gal.css("background",'url(' + $(this).attr('src') + ')');
//Assuming you want to set current image as background image
});
$( "img" ).mouseout(function(){
gal.css("background","none");
});
});
This is basic mechanism. You may have to change selector and path as per your requirement.
Fiddle: http://jsfiddle.net/NNGdR/5/
Upvotes: 1
Reputation: 130
You can assign the same class to each img. Example :
<img class="img-class" src="img1" />
<img class="img-class" src="img2" />
<img class="img-class" src="img3" />
<img class="img-class" src="img4" />
$(document).ready(function(){
var gal = $("#gal"); //Avoid repeated traverse
//Assign class so that this doesnt happen on other images in the html
$(".img-class").hover(function(){
gal.css("background",$(this).attr('src'));
//set current image as background
});
$( ".img-class" ).mouseout(function(){
gal.css("background","none");
});
});
This should work.
Upvotes: 1