jQuery
Image Source
Web Development
Programming
JavaScript

Changing the image source using jQuery

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Changing an image source with jQuery is usually just a matter of updating the src attribute. The common method is $(img).attr('src', newUrl), but in real code you often also care about timing, fallback behavior, and whether the new image actually loads.

So the basic answer is simple, but a robust answer also handles user interaction, preloading, and load errors.

The Basic Pattern

Use .attr() to change the src attribute.

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>

That is the core technique. Once the src changes, the browser starts loading the new image.

Toggling Between Images

A common UI pattern is switching between multiple images rather than just one fixed replacement.

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>

This pattern is common for galleries, theme previews, and product selectors.

Handling Load Errors

If the new image path is wrong, changing the src alone can leave a broken image on screen. Use the image error event to recover gracefully.

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>

That way, a missing or failed image can fall back to a safe default instead of showing a broken placeholder icon.

Preload Before Swapping

If you want to avoid visible flicker, preload the new image first and only swap after it is ready.

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 is useful for carousels and hero images where the user should not see a half-loaded transition.

Cache and Dynamic URLs

Sometimes developers think the image did not change when the browser is actually serving a cached file with the same URL. In development, a cache-busting query string can help.

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

Do not use cache-busting blindly in production for static assets, but it can be helpful for frequently regenerated images such as charts or screenshots.

jQuery vs. Plain JavaScript

If you are already using jQuery, .attr() is fine. If not, plain DOM code is equally straightforward.

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

This is worth noting because many modern projects no longer need jQuery for simple attribute updates.

Common Pitfalls

The biggest mistake is changing the src and assuming the image will always load successfully. Handle error events when the source may be unreliable.

Another common issue is thinking the swap failed when the browser actually served a cached image that looks unchanged.

People also replace large images instantly without preloading them, which can cause visible flicker or layout shifts.

Finally, if the project no longer depends on jQuery, using it only for a single .attr() call may be unnecessary overhead.

Summary

  • Use $(selector).attr('src', newUrl) to change an image source in jQuery.
  • Toggling among several images is just repeated src updates.
  • Use the error event to handle broken image URLs.
  • Preload large images before swapping to avoid flicker.
  • Cache can make an image appear unchanged even when the code ran correctly.
  • In modern codebases, plain JavaScript may be enough for this task.

Course illustration
Course illustration

All Rights Reserved.