Book Image

jQuery 2.0 Development Cookbook

By : Leon Revill
Book Image

jQuery 2.0 Development Cookbook

By: Leon Revill

Overview of this book

Table of Contents (17 chapters)
jQuery 2.0 Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Updating an image within a page


jQuery allows the developer to dynamically change images on a web page. This recipe will show you how to do this and also show you how to use a timestamp in order to prevent the browser from using a cached image, which can often be a problem when swapping images dynamically in this way.

Getting ready

For this recipe, you are going to need four different images. Ensure that you have four small images named black.png, red.png, blue.png, and green.png available.

How to do it…

To understand how jQuery can be used to change an image, complete each of the following steps:

  1. Create a file named recipe-8.html within an easily accessible directory, and add the following HTML code to this file:

    <!DOCTYPE html>
    <html>
    <head>
       <title>Change an image source and tackle browser caching to ensure it is always updated</title>
       <script src="jquery.min.js"></script>
       <script>
    
       </script>
    </head>
    <body>
       <img src="images/black.png" id="square" />
       <div>
          <button id="red-btn">Red</button>
          <button id="green-btn">Green</button>
          <button id="blue-btn">Blue</button>
       </div>
    </body>
    </html>
  2. Within the directory where the recipe-8.html file is created, create another directory called images and within this, add four images given as follows:

    • black.png

    • red.png

    • blue.png

    • green.png

  3. Add the following JavaScript within the <script></script> tags of recipe-8.html:

    $(function(){
       //Listen for a click on the red button
    $('#red-btn').click(function(){
       //When the red button has been clicked, change the source of the #square image to be the red PNG
       $('#square').prop("src", "images/red.png");
    });
       //Listen for a click on the green button
    $('#green-btn').click(function(){
       //When the green button has been clicked, change the source of the #square image to be the green PNG
       $('#square').prop("src", "images/green.png");
    });
    //Listen for a click on the blue button
    $('#blue-btn').click(function(){
       //When the blue button has been clicked, change the source of the #square image to be the blue PNG
       $('#square').prop("src", "images/blue.png");
    });
    });
  4. Opening this web page within a browser will allow you to change the source of the displayed image from the default black.png to another source depending on which button is clicked.

How it works…

To change the source of an image, we can use jQuery's prop() function and specify the new image name for the src property. To do this, when either of the buttons created using our HTML code are clicked, a click event handler is attached for each button using .click(), referencing the buttons' IDs, and then within the click() callback function,.prop() is executed with the appropriate image source specified, shown as follows:

$(function(){
$('#red-btn').click(function(){
   $('#square').prop("src", "images/red.png");
});

$('#green-btn').click(function(){
   $('#square').prop("src", "images/green.png");
});

$('#blue-btn').click(function(){
   $('#square').prop("src", "images/blue.png");
});
});

There's more...

This recipe illustrates the way a jQuery developer can easily change an image's source using a very simple example. A more realistic situation where this implementation will be used is within a web application where an image can be uploaded, for example, when a user chooses their avatar.

Traditionally, a user will be presented with a preview of their current avatar and then be able to choose an image from their computer to upload. Using AJAX, the web page can send this new image to the server; the server can then process and save this image and respond to the client web page. The web page, using jQuery's prop() method, can then update the current preview with the newly uploaded image and create a seamless transition without the need for the page to be refreshed in order to display the new image.

A problem occurs when the server uses the same filename for the new image as the old one. This is often the case when a user can only have one avatar; for the sake of simplicity, the avatar image is then saved using the user's unique ID (for example, 123.png).

When the server responds to the client with the new image filename, as the filename is the same, the browser will think that it is the same image. This may cause the browser to use the cached version of the avatar image, which will be the old image. To prevent this from happening, we can prepend a timestamp onto the image's filename. This will make the browser treat the image as new and force it to load the new image. We can modify the previous JavaScript to achieve the following:

$(function(){
$('#red-btn').click(function(){
     $('#square').prop("src", "images/red.png?t=" + new Date().getTime());
});

$('#green-btn').click(function(){
     $('#square').prop("src", "images/green.png?t=" + new Date().getTime());
});

$('#blue-btn').click(function(){
     $('#square').prop("src", "images/blue.png?t=" + new Date().getTime());
});
});

Using JavaScript's new Date() method, we create a new date that will be equal to the current date and time equal to the current time in milliseconds. We then use .getTime() to return a timestamp in milliseconds. When the source is updated, it will look as follows:

<img src="images/red.png?t=1371992012690" id="square">

This code will force the browser to reload the image using the newly specified source, provided the user does not update their image within the same millisecond (practically impossible).