0

Say for example I have two images called:-

<img alt="img-estate" src="images/estate.png" />

<img alt="img-saloon" src="images/saloon.png" />

On click of either of these images I want to be able to change the src to add -active on click.

So if I click on #img-estate the image src should be images/estate-active.png. So basically it reads the original src location and just adds -active on click.

How would I go about doing this using jQuery?

xdazz
  • 154,648
  • 35
  • 237
  • 264
nsilva
  • 4,976
  • 16
  • 57
  • 101

7 Answers7

3

The following will, following a click, effectively toggle the -active string:

$('img').click(function(){
    var src = this.src;
    this.src = src.indexOf('-active') == -1 ? src.replace('.png','-active.png') : src.replace('-active.png','.png');
});

If you'd rather just add that string:

$('img').click(function(){
    var src = this.src;
    this.src = src.replace('.png','-active.png');
});

To apply this to only those elements listed in the question, you could amend the selector to:

$('img[alt^="img-"]')

Which selects only those images whose alt attribute starts with the string img-.

Incidentally, if you'd prefer to use the jQuery attr() method, you don't have to call the same method twice to do so, simply use an anonymous function instead:

$('img[alt^="img-"]').attr('src', function(index, currentSrc){
    return currentSrc.replace('.png', '-active.png');
});

References:

David Thomas
  • 240,457
  • 50
  • 366
  • 401
1
$('img').click(function() {
  var $this = $(this);
  $this.attr('src', $this.attr('src').replace(/\.png$/, '-active.png'));
});
xdazz
  • 154,648
  • 35
  • 237
  • 264
1

Try this:

$('img').click(function(){
   var src = $(this).attr('src');
   src = src.substring(0, src.length-4);
   $(this).attr('src', src+'-active.png');
});
Alessandro Minoccheri
  • 34,369
  • 22
  • 118
  • 164
0

Ssomething like this might do the trick

$('img').on('click', function() {
   var $img = $(this);
   var currentSrc = $img.prop('src');
   $img.prop('src', currentSrc.replace('.png','-active.png'));
});

DEMO

Claudio Redi
  • 65,896
  • 14
  • 126
  • 152
0

This function should work perfectly:

$('img').click(function(){
    $(this).attr('src', $(this).attr('src').replace(/\.png/, '-active.png'));
}
Bill
  • 3,410
  • 21
  • 41
0

Firstly add a class to the image:

<img alt="img-estate" class="clickable_image" src="images/estate.png" />

$('.clickable_image).on('click, function(e){

      var source = $(e.target).attr('src').Split('.');
      $(e.target).attr('src','source[0] + '-active' + source[1]);



});
CR41G14
  • 5,224
  • 5
  • 42
  • 63
0
$(function() {
 $('img').click(function(){
 var image =  $(this).attr('src');
 alert(image);
 var newimage = image.replace('.png','-active.png');
 alert(newimage);

 $(this).attr('src',"newimage");
 return false;
 });
});

example

NullPointerException
  • 3,607
  • 5
  • 23
  • 57