jQuery Change Image Source Url


jQuery Change Image Source Url : Sometimes we need to change the image source url dynamically using jQuery or javascript. You can use jquery attribute method ie. .attr() to replace the image source url. Here in this tutorial we are going to explain how you can change the image source url using the jQuery.


jQuery Change Image Source Url

You can replace the image source url simply using the jQuery –

Syntax

jQuery Change Image Source Url : Syntax

$(selector).attr("src", newUrl);

You can use the above method to change image source url in jQuery. Add the image selector and provide the newUrl you want to change.

Example

Here is an example to change the image source url. You can replace the source url with new image source as below –

jQuery Change Image Source Url : Example

<script type="text/javascript">
function changeImageUrl(){
var newUrl = "http://example.com/images/new-image.jpg";
$("#myImage").attr("src", newUrl);
}
</script>
<img src="//example.com/images/old-image.jpg" id="myImage">
<button type="button" onclcik="changeImageUrl()">Change Image Url</button>

In the above example we have created a function which contains the script to change the image source. changeImageUrl() function is called on button click which will change the image source of image with id selector id=”myImage”.

jQuery Change Image Source Url


Advertisements

Add Comment

📖 Read More