Stuart Pontins Stuart Pontins - 2 months ago 36
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=""></img>';
case "colour2":
image = '<img src=""></img>';
case "colour3":
image = '<img src=""></img>';

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?


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)

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

function checkBoth() {

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