Stuart Pontins Stuart Pontins - 28 days ago 20
jQuery Question

Tracking two clicks and then producing an image

Is it possible to track 2 clicks and then produce an image based on those?

For example; I have here how to select one image and provide image based on that

var images = document.querySelectorAll('.img');

for (var i = images.length; i--;) images[i].addEventListener('click', change);

function change() {
switch (this.value) {
case "colour1":
image = '<img src="http://smallbeerpress.com/wp-content/uploads/itunes.png"></img>';
break;
case "colour2":
image = '<img src="http://fc01.deviantart.net/fs29/f/2009/238/d/8/Small_50x50__png_clock_pic_by_counter_countdown_ip.png"></img>';
break;
case "colour3":
image = '<img src="http://a.deviantart.net/avatars/r/a/rachelsrandomart.gif?12"></img>';
break;

default:
image = '<img src="#!"></img>';
}

document.getElementById("output-image").innerHTML = image;
}


But is it possible to check for 2 clicks before producing the image? One click would be for cupboards e.g. white cupboards and then another for worktop e.g. black worktop, then take this and pull the image with white cupboards and a black worktop?

Answer

What you need to do is to store the results of the clicks then only go to the image when both clicks are done.

The important points are:

  • create a couple of variables to store the selections
  • assign different classes to the images to relate them into A and B sections
  • modifying the click events to note the appropriate selection
  • and in the click event speculatively check if the other selection has been made yet

We only proceed to the image logic switch when we have some value in both selection A AND B.

// add variables to store selections
var selectionA = ""
var selectionB = ""

// change classes on the images to separate them
var imagesA = document.querySelectorAll('.imgTypeA');
var imagesB = document.querySelectorAll('.imgTypeB');

for (var i = imagesA.length; i--;) imagesA[i].addEventListener('click', changeA);
for (var i = imagesB.length; i--;) imagesB[i].addEventListener('click', changeB);

function changeA() {
    selectionA = (this.value)
    checkBoth()
}

function changeB() {
    selectionB = (this.value)
    checkBoth()
}

function checkBoth() {

    if (selectionA.length > 0 && selectionB.length > 0) {
    ...
    //logic for image selection using SelectionA & B values.
    ...
    }
}