If you want to dynamically update an image on your page you can use the jQuery change image src technique to select a new image.
You’ve probably done a bit of work with HTML before if you’re reading this and you’ll have come across the tag and how you set the src attribute to point to the file location of the image you want to load. So you’ll have something like this in your page:
You might want to display a different image to the user, maybe if they click a button or perform another action. We can use jQuery to change the image.
The jQuery change image src technique
The way it works is like this:
- Select an existing img element using jQuery
- Use jQuery to modify the src attribute of the img tag
- Replace the existing image reference with a new one
It’s dead simple really. We’ll use the jQuery *attr *function to change the source attribute. Here’s a quick example:
$(function(){
$('#logo').attr('src', '/images/new-logo.jpg');
});
The above code will change the image for the element with an id of *logo *and by setting the src attribute to *images/new-logo.jpg *as soon as the document has loaded. Of course, you probably don’t want to change the image straight away when the page loads (why not just set it in the img tag in the first place right?).
Changing the image on the click of a button
Probably a better use case is changing the image based on some action the user performs. Let’s take a look at changing the image on the press of a button.
$(function(){
$('#login').on('click', function(){
// Perform some login actions...
// ...
// Then update the login status image
$('#login-state').attr('src', 'images/loggedin.png');
});
});
It’s a bit out of context but you can image that the above snippet could form part of a login process. When the user clicks the button with the id of login *some login function is performed and then an img tag with the id of *login-state *is updated to show that the user is now logged in. *Note: There’s a lot missing from this example, e.g. what happens if the login fails etc. but it demonstrates how you might have a need to dynamically update an image in a real-world scenario.
Conclusion
To update images on a web page dynamically with jQuery it’s as simple as using the attr *function. Using this you can modify the *src **attribute of <img> **tags (or indeed any other attribute of any other tag!) to change the location of the image that is loaded. Enjoy creating something dynamic and awesome with this technique!