How to change img src with jQuery. Change the image url!

This article was written by in October 28, 2014, & may not be posted on other sites!
Original source url for this article: How to change img src with jQuery. Change the image url!

How to change img src with jQuery,
You can easily replace or change the image src with jQuery. This is how to change img src with jQuery:

How to change img src with jQuery. Change img url

 

Before starting to change the img src with jQuery

Before you can start working with jQuery, make sure you have included the jQuery library inside the <head> of your html document. Something like this:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>

 

How to change img src with jQuery, basics

To change the src of the img element, use this jQuery code:
$("#my-img").attr("src", "www.new-url.com/images/my-img.png");

 

How to change or alter img src with jQuery

To alter the img src further, change the img url or replace parts of the img src, the following code might be useful:

Put the current img src in a variable using jQuery
var currentUrl = $("#my-img").attr("src");

Add a value before the current img src using jQuery
var currentUrl = $("#my-img").attr("src");
currentUrl = "/thumbs/" + currentUrl;
$("#my-img").attr("src", currentUrl);

 

Spread the word

Facebooktwittergoogle_pluslinkedinmail

Leave a Reply

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