O'Reilly logo

jQuery and JavaScript Phrasebook by Brad Dayley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Changing an Image Source File

var imgArr = ["bison.jpg","peak.jpg","falls.jpg"]; var idx = 0; $(document).ready(function (){   $("img").on("click", function(){     if(idx<2) { idx++; } else { idx=0; }     $(this).attr("src", imgArr[idx]);   }); });

A common task in jQuery and JavaScript is changing the images displayed on the screen. Whether it is an online ad, a game, or an image gallery, it is much nicer to simply swap out the source file for an <img> element than reload the web page.

To change the image that is displayed in an <img> element, use the .attr("src", newImageURL) method to specify a new location of the new user file. When the src attribute changes, the browser automatically downloads the new image ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required