Reputation: 9855
I have a 5 rows on my website, each with an image in.
On click the image increases in size, but id then like to prepend a directory to the image source so it then becomes a different image.
Is this possible with jQuery?
Currently
<img src="image.jpg" />
What I want
<img src="hires/image.jpg" />
Ive read about using 'data-source' tags but I cant seem to get anything working?
Tried
$('img').click(function(){
$(this).attr({'src'}).prepend('hires');
});
Upvotes: 0
Views: 194
Reputation: 6000
$(this).attr({'src'}).prepend('hires');
There are a couple of things wrong in the above line.
{'src'}
is a SyntaxtError
. In JavaScript curly braces are used to create a new object (or a new block of code).
Objects are made up of key-value pairs, such as
var obj = { aKey: 42 };
obj.aKey // 42
Update. Since ES2015 it's possible to omit the value, in case a variable with the same name of the key exists, and is accessible in the scope where the object is being created.
var aKey = 42;
var obj = { aKey }; // Note, there're no quotes
obj.aKey // 42
$.fn.attr work both as getter, both as setter on the basis of the arguments it receives.
You may want to use it as $(this).attr('src')
to get the current src
attribute, and $(this).attr('src', 'something')
to update it.
$.fn.prepend does not work on string. It's used to insert content, to the beginning of each matching element.
So finally that's the correct way to achieve your objective:
$(this).attr('src', 'hires/' + $(this).attr('src'));
Upvotes: 1
Reputation: 816560
Is this what you are looking for?
$('img').click(function(){
$(this).attr('src', function(i, value) {
return 'hires/' + value;
});
});
It would prepend hires/
on each click though. You can test whether it was already there using .indexOf
:
$(this).attr('src', function(i, value) {
return value.indexOf('hires/') === -1 ? 'hires/' + value : value;
});
If you want to toggle between hires/
and not hires/
, remove the string if it is present:
$(this).attr('src', function(i, value) {
return value.indexOf('hires/') === -1 ?
'hires/' + value :
value.replace('hires/', '');
});
.prepend
is a jQuery method to add DOM elements. It's not a native string method. Also the curly brackets are wrong there (syntax error).
Upvotes: 6
Reputation: 148140
You can do it this way,
$('img').click(function(){
$(this).attr('src', function(i, value) {
return 'hires/' + value;
});
});
Upvotes: 1
Reputation: 8266
This should do it:
$('img').click(function(){
var imgSRC = $(this).attr('src');
$(this).attr('src', 'hires/' + imgSRC);
});
Upvotes: 1