Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
jQuery 2.0 Development Cookbook

You're reading from   jQuery 2.0 Development Cookbook As a web developer, you can benefit greatly from this book - whatever your skill level. Learn how to build dynamic modern websites using jQuery. Packed with recipes, it will quickly take you from beginner to expert.

Arrow left icon
Product type Paperback
Published in Feb 2014
Publisher Packt
ISBN-13 9781783280896
Length 410 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Leon Revill Leon Revill
Author Profile Icon Leon Revill
Leon Revill
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Document Object Model Manipulation FREE CHAPTER 2. Interacting with the User by Making Use of jQuery Events 3. Loading and Manipulating Dynamic Content with AJAX and JSON 4. Adding Attractive Visuals with jQuery Effects 5. Form Handling 6. User Interface 7. User Interface Animation 8. Understanding Plugin Development 9. jQuery UI 10. Working with jQuery Mobile 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).

You have been reading a chapter from
jQuery 2.0 Development Cookbook
Published in: Feb 2014
Publisher: Packt
ISBN-13: 9781783280896
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image