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
  • 158,678
  • 38
  • 247
  • 274
nsilva
  • 5,184
  • 16
  • 66
  • 108

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
  • 249,100
  • 51
  • 377
  • 410
1
$('img').click(function() {
  var $this = $(this);
  $this.attr('src', $this.attr('src').replace(/\.png$/, '-active.png'));
});
xdazz
  • 158,678
  • 38
  • 247
  • 274
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
  • 35,521
  • 22
  • 122
  • 171
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
  • 67,454
  • 15
  • 130
  • 155
0

This function should work perfectly:

$('img').click(function(){
    $(this).attr('src', $(this).attr('src').replace(/\.png/, '-active.png'));
}
Bill
  • 3,478
  • 23
  • 42
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,464
  • 5
  • 43
  • 64
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,732
  • 5
  • 28
  • 62