📖 jQuery Images

Rollover Images

Rollover images is a behavior that changes the image source when the mouse is moved over the image then changes back to the original image when the mouse is moved off the image. One simple method is to use jQuery events and attr method to change the src of the image.

/* Using mouseover/mouseout() functions */
$('#photo').mouseover(function() {
      $('#photo').attr('src', 'images/newImage.jpg');
});
$('#photo').mouseout(function() {
      $('#photo').attr('src', 'images/origImage.jpg');
});
 
/* Using hover() function */
$('#photo').hover(
function() {
	$('#photo').attr('src', 'images/newImage.jpg');
},
function() {
	$('#photo').attr('src', 'images/origImage.jpg');
});

Using the simple method above, the browser has to download the new image when you mouseover the photo which may result in a delay. To avoid the delay, you can preload the image(s):

var newPhoto = new Image(); // creates a new image object
newPhoto.src = 'images/newImage.jpg'; // assigns a value to the src attribute 

$('#photo').mouseover(function() { // perform function during #photo mouseover event
	$('#photo').attr('src', newPhoto.src); // assigns the new image src to #photo
});

If you have multiple rollover images, you can use an array and a loop to preload them all.

// create an array of all the rollover images. Include as many as you need, separated by commas
var preloadImages = ['images/image1.png', 'images/image2.png', 'images/image3.jpg'];
// create a new empty array called imgs for the preloaded image objects
var imgs = [];
// use a for loop to loop through the preloadImages array and create an image object with a src attribute for each one
for (var i = 0; i < preloadImages.length; i++) {
	imgs[i] = new Image();
	imgs[i].src = preloadImages[i];
}

You can also use the hover event to toggle your images (this example does not use the array method).

// create the image object for the new image and assign the src attribute a value
var newPhoto = new Image();
newPhoto.src = 'images/newImage.jpg';
// capture the src attribute of the img object in the html to use for the mouseout event
var oldSrc=$('#photo').attr('src');
// set the functions for the hover event to change src attribute on mouseover and mouseout
$('h1').hover(
function() {
	$('#photo').attr('src', newPhoto.src);
},
function() {
	$('#photo').attr('src', oldSrc);
}); // end hover
Image gallery

 You can change the src attribute of any image based on an event. To create an image gallery, you can display thumbnails of all your images along with a large version on one image. When you click on one of the thumbnails, you can change the src attribute of the larger image to match the smaller one. This is a simplified version of what is used in the book. In this example, I am using the same image for the thumbnail and the larger image and just altering the height and width attributes in the html to change the display size. This way, I don't have to preload the images since they are loaded in the page already. The thumbnail images are in a div with id="gallery" and the larger image has an id="lgPic".

$(document).ready(function() {
	// loop through all img tags in the #gallery div (thumbnail images)
	$('#gallery img').each(function() {
		// get the src attribute of the thumbnail image
		var imgFile = $(this).attr('src');
		// when the image is clicked, assign the src attribute to the lgPic
		$(this).click(function() {
			$('#lgPic').attr('src', imgFile);
		});// end click
	}); // end each
}); // end ready

Of course, you can add a hover action to the gallery images or effects on lgPic to further enhance the appearance of your photo gallery.

Selecting Links
$('a')
select all links on a page.
$('#idname a')
select all links in an id.
$('a[rel="external"]')
select all links with a particular attribute such as rel="external".
$('a[href$=".pdf"]')
select all links that point to a file with a particular pattern such as all pdf files.
^= begins with the value
$= ends with the value
*= contains the value anywhere in the string
.attr('href')
to determine the destination of the link.
Prevent a page from following a link
  • Select the link
  • Assign the click event
  • Create the alternate action to be taken
  • Stop the link from going to the destination href using return false; or evt.preventDefault();

Example

Select all links with rel="external" and alert the user they cannot go to that page.

$('a[rel="external"]').click(function() {
	alert($(this).attr('href') + " cannot be viewed at this time");
	return false;
});
/* OR */
$('a[rel="external"]').click(function(evt) {
	alert($(this).attr('href') + " cannot be viewed at this time");
	evt.preventDefault();
});
Open links in a new window

Add target="_blank" to the link. You can also do this for selected links on a page with jQuery instead of hard-coding in html.

$('a[rel="external"]').attr('target', '_blank');

Alternately, if you set the target attribute to a value, all the windows will open in the same new window instead of creating a new window each time.

$('a[rel="external"]').attr('target', 'newWin');
Create a new window

Creating a new window with JavaScript gives more control over the properties of the window (size, location, etc.).

Format: open(URL, name, properties)

URL is the url of the page to be displayed in the window
name is a variable name you assign to the window
properties are the settings for the window

You can also assign a variable name to the window so you can reference it later in your JavaScript

var newWin = open(URL, name, properties);
New Window Properties
PropertyDefinition
height = pixels The height of the window. Min. value is 100
left = pixels The left position of the window
location = yes|no Whether or not to display the address field. Default is yes. May be ignored by some browsers.
menubar = yes|no Whether or not to display the menu bar. Default is yes
resizable = yes|no Whether or not the window is resizable. Default is yes
scrollbars = yes|no Whether or not to display scroll bars. Default is yes
status = yes|no Whether or not to add a status bar. Default is yes
titlebar = yes|no Whether or not to display the title bar. Ignored unless the calling application is an HTML Application or a trusted dialog box. Default is yes
toolbar = yes|no Whether or not to display the browser toolbar. Default is yes
top = pixels The top position of the window.
width = pixels The width of the window. Min. value is 100

Example

To open a window that is 500 by 500 pixels with no menubar and no location bar at a specific location.

$('a[rel="external"]').click(function() {
	newWin = open($(this).attr('href'), 'popWin', 'width=640, height=480, top=100, left=200');
	return false;
});

To close a window you have opened, use .close() function. For example to close the window we opened above: newWin.close();

Other Window Methods
MethodDescription
.blur() Removes focus from the current window
.close() Closes the current window
.focus() Sets focus to the current window
.open() Opens a new browser window