Forums >> Programming >> Proof of Concept (POC) >>
Using jQuery to Change an Image SRC (source) Attribute


Using jQuery to Change an Image SRC (source) Attribute

Using jQuery to Change an Image SRC (source) Attribute

We recently added the option to include a picture for your profile.  You can find this in the User Control Panel (User CP) by clicking on your user ID when signed in.

A lot of sites allow you to upload your own image to the site.  But, with the cloud and so many hosting sites, we chose to allow you to specify the path to a file somewhere on the net.  In other words, why should we store it, when it is most likely already stored on a cloud drive somewhere, such as One Drive, Google Drive, or Photo Bucket.

To make sure the proper path is entered, we added functionality that will show the picture below the value.  

See the example below:

If we change the path, the picture also changes:

This is all done with the magic of jQuery.  And, it's a lot easier than you may think.

Below is a snippet of the HTML source code for the web page:

		<td valign="top">
			Profile Picture:<br>
			<span class="small3">(will be reduced to 50x50)</span>
			<input size="100" id="newProfilePicture" name="profpic" value="/%profpic%/"> 
			<img id="profilePicture" height="50" width="50" src="/%profimg%/">

You'll see that we have ID attributes for the input field that holds the path to the image file, as well as for the picture (<IMG> tag) itself.

In days past, we would have done something like a JavaScript function on the input for when the cursor leaves the field to execute some JavaScript to change the source of the image file to the new value.  But with jQuery, it's even easier.

	$('#newProfilePicture').blur(function() {
		var newSrc = $('#newProfilePicture').val();

The blur() method is used on the input field, and when it fires (because the cursor left the field) we use the attr() method on the image to change the SRC attribute.

This is where IDs come in very handy when naming objects.  Classes can also be used, but in this case we are performing a very specific operation, so we want to use a unique ID on each of the HTML objects.  (And IDs on web pages NEED to be unique, or jQuery just won't work right... don't ask me how I know that!)

It's really just that simple!

Last edited 07/26/2015 at 14:22:45


Copyright 1983-2017 BVSTools
GreenBoard(v3) Powered by the eRPG SDK, MAILTOOL Plus!, GreenTools for Google Apps, jQuery, jQuery UI, BlockUI, CKEditor and running on the IBM i (AKA AS/400, iSeries, System i).