jquery – Change event.target src attr in JavaScript-ThrowExceptions

Exception or error:

On clicking image I want to change its src attribute using event.target.

I am trying to achieve the same using below code but it is not working; where am I going wrong?

$(".sim-row-edit-img").click(function(){
	alert("Image clicked");
	$("event.target").attr("src","https://cdn.iconscout.com/icon/free/png-256/car-location-find-navigate-gps-location-29571.png");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="sim-row-edit-img" border="0" alt="W3Schools" src="http://icons.iconarchive.com/icons/dtafalonso/android-l/256/WhatsApp-icon.png" width="100" height="100">
How to solve:

event.target is an object , so remove the quotes from event.target

$(".sim-row-edit-img").click(function() {
  alert("Image clicked");
  $(event.target).attr("src", "https://cdn.iconscout.com/icon/free/png-256/car-location-find-navigate-gps-location-29571.png");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="sim-row-edit-img" border="0" alt="W3Schools" src="http://icons.iconarchive.com/icons/dtafalonso/android-l/256/WhatsApp-icon.png" width="100" height="100">

###

You should use $(this).attr() as $('event.target') will not give you a valid jQuery object. Using $(this) will give you the reference of the clicked element and then you can change the src attribute of that element.

$(".sim-row-edit-img").click(function() {
  alert("Image clicked");
  $(this).attr("src", "https://cdn.iconscout.com/icon/free/png-256/car-location-find-navigate-gps-location-29571.png");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="sim-row-edit-img" border="0" alt="W3Schools" src="http://icons.iconarchive.com/icons/dtafalonso/android-l/256/WhatsApp-icon.png" width="100" height="100">

To use event.target you need to pass the event object to the function and no need to use $(event.target), simply use event.target.src = 'value'.

$(".sim-row-edit-img").click(function(event){
	alert("Image clicked");
	event.target.src = "https://cdn.iconscout.com/icon/free/png-256/car-location-find-navigate-gps-location-29571.png";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<img class="sim-row-edit-img" border="0" alt="W3Schools" src="http://icons.iconarchive.com/icons/dtafalonso/android-l/256/WhatsApp-icon.png" width="100" height="100">

Leave a Reply

Your email address will not be published. Required fields are marked *