Farhang Farhang - 1 year ago 67
CSS Question

css font and background styling for a javascript (dynamic) form

I was hoping to get some help on styling that goes over my head. I found this tic-tac-toe fiddle randomly online:


This is not my fiddle but it speaks to my problem of dynamic styling when JS is involved.

The first click on a square generates "x" and then the computer plays by placing "o" in another square.

My questions: how does one style the squares after each click. For instance, any "x" square becomes blue and any "o" square becomes red.

  1. Is it possible to do this with css only?

  2. If not pure css, where in JS does one do this?

PS: I am an amateur learning on my own slowly. Stackoverflow has been so helpful and usually reading previous questions/answers is enough. Although I have seen roughly similar questions, I could not find this exact issue.

Thank you for your help.

Answer Source

Here is a JavaScript solution to what you are trying to achieve: Modified fiddle of the link you provided

Hacky solution, but what I did was modify the form element. Whenever the user clicks on the form it will loop through all the elements, and if it is a tictac square it will check the elements value. And style according to the value inside of the square.

Main thing, you can style elements with JavaScript the following way:

someElement.style.background = 'colorString';

<FORM NAME="tic" onclick='
  for(var i = 0; i < this.children.length; ++i){
    if(this.children[i].className === "tictac"){
      if(this.children[i].value === " X "){
        this.children[i].style.background = "blue"; // new style for X
      }else if(this.children[i].value === " O "){
        this.children[i].style.background = "red"; // new style for O
        this.children[i].style.background = "rgb(221,221,221)"; // style for empty square
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download