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 ...

Get jQuery and JavaScript Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.