Last image standing

For a small project that hopefully will reach some level eventually.
At some point after many efforts I tried the following code:

  <div id="ttt">
  <div class="ttt_grid">
    <div id = "ttt1" class = "tttcell"><img src="./blank.svg"></div>
    <div id = "ttt2" class = "tttcell"><img src="./blank.svg"></div>
    <div id = "ttt3" class = "tttcell"><img src="./blank.svg"></div>
    <div id = "ttt4" class = "tttcell"><img src="./blank.svg"></div>
    <div id = "ttt5" class = "tttcell"><img src="./blank.svg"></div>
    <div id = "ttt6" class = "tttcell"><img src="./blank.svg"></div>
    <div id = "ttt7" class = "tttcell"><img src="./blank.svg"></div>
    <div id = "ttt8" class = "tttcell"><img src="./blank.svg"></div>
    <div id = "ttt9" class = "tttcell"><img src="./blank.svg"></div>
  </div>
  <button id = "reset"> reset </button>
  </div>
turn = 0;
images = {0:'./X.svg',1:'./O.svg'}
$(".tttcell").each(function(){
   theImg = $(this).find("img");
   $(this).bind('click',function(e){
      if (theImg.attr('src') == './blank.svg')
      {
      	theImg.attr({src:images[turn]});
      	turn = 1-turn;
      }
   });
});

This code affects only the last image (div id ttt9), the reason may be that theImg is overwritten after every each(). So the solution was:

turn = 0;
images = {0:'./X.svg',1:'./O.svg'}
$(".tttcell").each(function(){
   $(this).bind('click',function(e){
      theImg = $(this).find("img");
      if (theImg.attr('src') == './blank.svg')
      {
      	theImg.attr({src:images[turn]});
      	turn = 1-turn;
      }
   });
});

It will take me a while to get into the javascript mindset.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s