Tag Archives: DOM images

Changing An Image Based On A Checkbox Check Via jQuery / JavaScript

This question came via email earlier today:

Your Article: An Image-Based ‘Checkbox’
http://www.dougv.com/demo/js_imgswap_checked/example2.html

Awesome article and very informative. I was trying to get it to work for what I am trying to accomplish but I am having a hell of a time getting it to work I was hoping you can help me.

I have a selection form based on Check Boxes:

item 1 (box)
item 2 (box)
item 3 (box)
item 4 (box)

I have images that correspond to the check boxes, item1.png, item2.png, item3.png, item4.png that are located elsewhere on the page. I just need the image to change based on whether the check box is checked or not. It doesn’t matter if it is faded or an entirely new image, so long as the user notices which box they checked. My problem is there are a lot of little images so in your example you had the two set variables, on or off. How do I introduce multiple images???

I have early tests and the problems are that the default unchecked images do not show up until after the check box is checked…all of them and two whenever I try to add multiple images and or check boxes it breaks somewhere, perhaps the array or I am approaching this at the wrong end. I need your help.

To rephrase the question:

  • We have four checkboxes inside a form.
  • On the same page, we have four images. Each image is related to one of those checkboxes. That is, Checkbox 1 is related to Photo 1, Checkbox 2 is related to Image 2, etc.
  • When we click a checkbox, we want to change its associated image somehow, to indicate the checkbox’s state. (In this case, I am going to use a faded image if its related checkbox is unchecked, and a full-opacity image if its related checkbox is checked).

Easily enough accomplished.

For this exercise, I will use four pictures of Miss USA 2012 contestants, and ask users to pick which are their favorites. If a contestant is selected, her picture will be at full opacity; if the contestant is not selected, her image will be at reduced opacity (i.e., faded).
Continue reading

Preloading Images With JavaScript

Anne Hathaway

Anne Hathaway photo by Brian Smith

In my recent travels through old blog posts, I’ve noticed a number of occasions where I’ve discussed how to preload images.

Almost all those examples are stupid or just plain wrong. For that, you have my apologies, and I aim to rectify those mistakes with this post.

First, why would we want to preload an image? Simply put, we intend to show it later on our Web page — either as a result of a mouseover, or a click, or some other sort of Document Object Model (DOM) event.

For example, maybe we want to mouseover a series of thumbnails, and show a larger version of that image in the same place.

Rather than making the end user wait for a new image to load as a result of doing something on a Web page, it makes sense to load the image we intend to show in advance, so it will display almost instantaneously as a result of an event.

I’ll first show why two of my previous methods for preloading images are wrong or dumb, then describe two correct ways to preload images: via basic JavaScript and via jQuery.

The lovely Anne Hathaway will be our model.
Continue reading

Automatically Wiring Up XHTML Element Events On Page Load With jQuery

Many Web developers find themselves in an environment where the design of a Web page is handled by a graphic designer or junior programmer, either as part of their team or from a subcontractor or the client himself.

Unfortunately, traditional HTML / XHTML requires most element events handlers — onmouseover, onclick, onfocus, etc. — to be coded as attributes of the tag, like this:

<img id="myimage" src="pic1.jpg" alt="My Image" onmouseover="this.src='pic2.jpg'" onmouseout="this.src='pic1.jpg'" />

That’s not a problem if you’re the end point of the code; that is, if the graphic designer hands you a final page that won’t be modified again. But in the real world, pages and their associated code need to be moved back and forth constantly, with changes aplenty. That can have a real impact on your work, especially if the designer changes or removes your event handlers from page elements.

That’s the idea behind MVC (model, view, controller). We break the chain of custody for a Web request into three parts: A controller accepts a request from the user and determines which model should be used to handle the request.

The selected model, in turn, does something with the request sent to it by the controller; for example, one model might serve up some static content; another model returns search query results; another model returns data based on an environment variable, such as the geolocation of the user’s IP address (that is, gives a page in Russian to a user from Russia, by default); and so on.

Finally, the view — the end output the user sees — is applied by the controller to the model’s results.

While this is a worthwhile development approach, it may be a bit of overkill for a site that doesn’t have too much dynamic content, or that simply needs an image rollover effect, a countdown clock, etc. We still want to protect our coding from alteration by the designer, but we don’t want to employ a $10 solution to a 10-cent problem.

Enter, once again, jQuery, which can automatically bind (that is, “wire up”) event handlers for us once the page loads.

Continue reading

JavaScript Function Arguments: They’re An Array And You Can Treat Them As Such

One of the nicest features of JavaScript is the ability to treat function arguments as an array. We all know how to write a function that takes a known number of arguments:

function foo(bar) {
	alert(bar);
}

function getArea(shape, measure, unit) {
	var output = 'The area of a ' + measure + ' ' + unit + ' ' + shape + ' is ';
	switch(shape) {
		case 'square':
			output += (measure * measure);
			break;
		case 'circle':
			output += (3.14 * (measure * measure));
			break;
		default:
			output += 'unknown to this function.';
	}
	alert(output);
}

But sometimes, your script will require you to pass some unknown number of parameters to a function. So how do you deal with that?

Luckily, JavaScript functions treat all of their arguments as an array. So, if you’re not certain how many arguments your function will take, don’t declare them in your function code; simply use the reserved word arguments to iterate the array of arguments passed to the function.

Continue reading

The Simplest Ways To Do Image Rollover Effects: JavaScript And CSS-Only

A common question on Yahoo! Answers is how to do image rollover effects simply.

There are two ways to do so: With JavaScript, and via CSS alone. Of the two, I prefer the JavaScript method, as it doesn’t require marking up your code too much; but the CSS method is fine, too, and takes away the worry of dealing with users who have disabled JavaScript in their browsers.

This topic also allows me to address the best way to “preload” images for use via JavaScript / CSS; previous articles I’ve written have used less efficient methods, and I’d like to go on record with the proper way to preload.

Last things first, then. The proper way to “preload” images is to use a standard XHTML img tag, using a CSS class to “hide” the image(s) being preloaded via display: none. These images should then appear directly before the closing body tag, to speed page loading by loading the “preloaded” images last.

img.hide {
        display: none;
}
        <img src="home-over.png" alt="" class="hide" />
        <img src="about-over.png" alt="" class="hide" />
        <img src="services-over.png" alt="" class="hide" />
        <img src="contact-over.png" alt="" class="hide" />
</body>

Using CSS to hide images should work for all current Web browsers, including versions 5+ of Internet Explorer.

Continue reading