views:

947

answers:

1

I am trying to swap image when an image is clicked...here is my jquery so far and it's not working.

$(document).ready(function(){
imgFldr = '../../App_Themes/Default/Images/';
    $('#smallImg1').click(function(){

     $('#smallImg1').attr('src', imgFlder+'belkinSmall4.png');
    });
});

And below is an example of my HTML

<div>
     <img id="smallImg1" src="../../App_Themes/Default/Images/belkinSmall1.png" />
</div>

Any help would be appreciated!

+1  A: 

I would have written it like this:

$(function() {
  var imageFolder = '../../App_Themes/Default/Images/';
  $('#smallImg1').click(function(){
    $(this).attr('src', imageFolder + "belkinSmall4.png");
  });
});
  • $(function() { ... }) is shorthand for $(document).ready(function() { ... })
  • imageFolder instead of imgFldr. Pointless abbreviation imo.
  • var imageFolder, too (var is the key here), so that it is a local variable, not a global.
  • $(this) instead of $('#smallImg1'), to avoid duplications. The result is identical.

However, this is just a re-factoring of your code — both your snippet and mine should work.

So, "doesn't work" - does the image change? Is the path invalid? Do you get any JS runtime errors? What if you set the src to '../../App_Themes/Default/Images/belkinSmall4.png' by hand — does the image exist?

August Lilleaas