View Full Version : jQuery function to change the source of an image???

02-26-2011, 09:47 AM
Hello all. I am trying to make a function in jQuery that will change the SOURCE of an image. This is what I have so far but it does not work :( . How can this code be altered to change the source of an image???

function changeImage(imageName,imageSrc){
//This works, but I want to try it in jQuery style function
//document.getElementById(imageName).src = imageSrc;

//This does not work, there is something wrong with imageName
$("#imageName").attr("src", imageSrc);

The way I currently have my images is like this:

<a href="#" onmouseover="changeImage('home','./images/home_over.png');" onmouseout="changeImage('home','./images/home_under.png');">
<img id="home" name="home" src="./images/home_under.png" alt="HOME &amp; UPDATES" />

02-26-2011, 03:19 PM
Might not be the most graceful solution but a solution none the less:

<!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">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Scroll :: easy version ;)</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function imgSwap(){
$('#nav a').hover(function(){
oldSRC = $(this).children('img').attr('src');
newSRC = $(this).attr('rel');
$(this).children('img').attr('src', newSRC);
}, function(){
$(this).children('img').attr('src', oldSRC);


<style type="text/css">



<div id="nav">
<a href="#" rel="http://farm6.static.flickr.com/5219/5478414806_41fe7057ee_t.jpg">
<img src="http://farm6.static.flickr.com/5096/5475741180_6c392a2c21_t.jpg" alt="" />
<a href="#" rel="http://farm6.static.flickr.com/5296/5478454563_e8262f8da2_t.jpg">
<img src="http://farm6.static.flickr.com/5058/5479010072_399d18ebe1_t.jpg" alt="" />