Reputation: 769
I am in a (steep) learning cuve with JS. I would suppose my JS code will only trigger action for image with src attribute : "http://placehold.it/350x150" to change to the targeted new link (320x120) on click. but it changes ALL images to the latest, any idea plz ?
Complete code: http://jsfiddle.net/celiostat/nmH8L/34/
HTML:
<img class=icon1 src="http://placehold.it/350x150"/>
<img class=icon2 src="http://placehold.it/140x140"/>
<img class=icon3 src="http://placehold.it/200x100"/>
<img class=icon4 src="http://placehold.it/350x65"/>
JS:
$(document).ready(function() {
$('.icon3').on("click", function() {
if($('img').attr('src') === 'http://placehold.it/350x150')
$('img').attr('src', 'http://placehold.it/300x120');
})
})
Upvotes: 0
Views: 158
Reputation: 2857
If you want to resume back the former image to it's initial state, then for each click event you should do the following.
$('.icon1').on("click", function (e) {
if ($(e.currentTarget).attr('src') === 'http://placehold.it/350x150') {
var changedImage = $('[data-image-name="changed_image"]')
changedImage.removeAttr('data-image-name').attr('src', changedImage.attr('prevSrc'));
$(e.currentTarget).attr('data-image-name', 'changed_image');
$(e.currentTarget).attr('prevSrc', 'http://placehold.it/350x150');
$(e.currentTarget).attr('src', 'http://placehold.it/300x150');
}
})
Upvotes: 2
Reputation: 616
Change your code to
$(document).ready(function() {
$('image').on("click", function() {
if($('img').attr('src') === 'http://placehold.it/350x150')
$(this).attr('src', 'http://placehold.it/300x120');
})
})
Upvotes: 0
Reputation: 944455
$('img')
selects all image elements. Use $(this)
to get the element the event fired on.
Upvotes: 1