Search code examples
javascriptimageonclickgetelementbyidswap

Multiple Image swap


I have 10 images of an empty black square. Below them, I have 10 black boxes labeled 0-9. My goal is to allow the user to click on a numbered square, and select which blank square he wants to place it.

The user must be able to do this with every numbered square. (I have a math problem that I want the user to solve by clicking the images and put them where they need to go to solve the equation). My train of thought was to obtain the image clicked by using getElementId and storing it into a variable, and continue the process.

I'm not sure if this is possible. My thinking was "Click image, identiy what was clicked, store it in a temporary variable holder, and swap with the second (blank) image clicked).

My HTML:

These are the blank images 0-9:

<img src="blank.jpg" id="blank0" onclick="swap()" width="30" height="30">  </button>
<img src="blank.jpg" id="blank1" onclick="swap()" width="30" height="30">  </button>

etc. etc.

These are the numbered images:

<img src="0.jpg" id="0" onclick="" width="30" height="30">  </button>
<img src="1.jpg" id="1" onclick="" width="30" height="30">  </button>

etc.


Solution

  • Try something like this:

    (top of all JS):

    var holder = '';
    var holderId = '';
    

    Then add this to numbered images:

    <img src="0.jpg" id="number0" onclick="setHolder(this.src,this.id)" width="30" height="30">
    

    And this to blank:

    <img src="blank.jpg" id="blank0" onclick="swapHolder(this)" width="30" height="30">
    

    Then create the two functions like this:

    function setHolder(src,id) {
        holder = src;
        holderId = id;
    }
    
    function swapHolder(img) {
        img.src = holder;
        document.getElementById(holderId).src = 'blank.jpg';
        holder = '';
        holderId = '';
    }