Reputation: 5622
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?
Upvotes: 0
Views: 629
Reputation: 3814
$(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;
});
});
Upvotes: 0
Reputation: 253506
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:
Upvotes: 3
Reputation: 5594
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]);
});
Upvotes: 0
Reputation: 3517
This function should work perfectly:
$('img').click(function(){
$(this).attr('src', $(this).attr('src').replace(/\.png/, '-active.png'));
}
Upvotes: 0
Reputation: 35973
Try this:
$('img').click(function(){
var src = $(this).attr('src');
src = src.substring(0, src.length-4);
$(this).attr('src', src+'-active.png');
});
Upvotes: 1
Reputation: 160963
$('img').click(function() {
var $this = $(this);
$this.attr('src', $this.attr('src').replace(/\.png$/, '-active.png'));
});
Upvotes: 1
Reputation: 68440
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'));
});
Upvotes: 0