Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying jQuery 2.0 Development Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
jQuery 2.0 Development Cookbook

jQuery 2.0 Development Cookbook

By : Leon Revill
4.2 (12)
close
close
jQuery 2.0 Development Cookbook

jQuery 2.0 Development Cookbook

4.2 (12)
By: Leon Revill

Overview of this book

Taking a recipe-based approach, this book presents numerous practical examples that you can use directly in your applications. The book covers the essential issues you will face while developing your web applications and gives you solutions to them. The recipes in this book are written in a manner that rapidly takes you from beginner to expert level. This book is for web developers of all skill levels. Although some knowledge of JavaScript, HTML, and CSS is required, this Cookbook will teach jQuery newcomers all the basics required to move on to the more complex examples of this book, which will benefit the more seasoned jQuery developer. If you want to learn how to create modern website features quickly, using best practice techniques, then this book is for you.
Table of Contents (12 chapters)
close
close
11
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).

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
jQuery 2.0 Development Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon