jQuery
Image Source
Web Development
Programming
JavaScript

Change an image src with jQuery

Codemia Knowledge Hub ·

To change an image source with jQuery, update its src attribute with .attr(): $(img).attr('src', newUrl). The browser starts loading the new image as soon as the attribute changes. In real code you may also want to handle load errors, preload large images, and watch out for caching.

Basic swap with .attr()

This is the core technique: select the image, then set a new value for its src attribute, here in a click handler.

html
1<img id="photo" src="old.jpg" alt="Product photo">
2<button id="swap">Swap image</button>
3
4<script>
5  $("#swap").on("click", function () {
6    $("#photo").attr("src", "new.jpg");
7  });
8</script>

Cycling through several images

Galleries, theme previews and product selectors switch between several images. That is just repeated src updates:

html
1<img id="gallery" src="image1.jpg" alt="Gallery image">
2<button id="next">Next</button>
3
4<script>
5  const images = ["image1.jpg", "image2.jpg", "image3.jpg"];
6  let index = 0;
7
8  $("#next").on("click", function () {
9    index = (index + 1) % images.length;
10    $("#gallery").attr("src", images[index]);
11  });
12</script>

Falling back when the image fails to load

If the new path is wrong, changing src leaves a broken image on screen. Handle the image's error event to swap in a safe default, especially when the source may be unreliable:

html
1<img id="avatar" src="user.jpg" alt="Avatar">
2
3<script>
4  $("#avatar").on("error", function () {
5    $(this).attr("src", "fallback-avatar.png");
6  });
7</script>

Preloading before the swap

Swapping in a large image instantly can cause visible flicker or layout shifts. Preload it first and change src only once it has loaded:

javascript
1function swapImage($img, nextSrc) {
2  const preloader = new Image();
3
4  preloader.onload = function () {
5    $img.attr("src", nextSrc);
6  };
7
8  preloader.onerror = function () {
9    console.error("failed to load", nextSrc);
10  };
11
12  preloader.src = nextSrc;
13}
14
15swapImage($("#photo"), "new.jpg");

This helps with carousels and hero images, where users should not see a half-loaded transition. The onerror handler also gives you a place to log or recover when the new image cannot be loaded, instead of leaving the old one in place silently.

When the image seems not to change

If the URL stays the same, the browser may serve a cached copy, which looks as though the code did nothing. A cache-busting query string forces a fresh request:

javascript
const url = "chart.png?t=" + Date.now();
$("#chart").attr("src", url);

Do not apply this blindly to static assets in production, but it is useful for images that are regenerated often, such as charts or screenshots.

Doing it without jQuery

If the project already uses jQuery, .attr() is fine. If it does not, loading jQuery for a single attribute update is unnecessary, since plain DOM code is just as short:

javascript
document.getElementById("photo").src = "new.jpg";

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms