Y S
Y S

Reputation: 76

contenteditable change background color after edit

I am trying to build a spreadsheet-like application and using a table <td> with a tag contenteditable = "true" and I want the background color of the cell to be changed after it was changed.

From my research I figured I would need javascript or jquery to do so, however I know very little of it. Where do I start? So far I have figured how to change color when the cell is being edited. thank you!

<td contenteditable="true" >
  <style>
     [contenteditable="true"]:focus {
       background-color: yellow;
     }
  </style>
  "Stuff"
</td>

Upvotes: 0

Views: 1203

Answers (2)

Andrew L
Andrew L

Reputation: 5496

So I see you figured out how to change color when the cell is being edited. Now to change the cell after its done being edited you can use the following example.

jQuery has a function called focusout which triggers when the element loses focus from the user. It will then add the class orange which will change the background to orange.

$( document ).ready(function() {
  $("td").focusout(function(){
      $(this).addClass("orange");
  });
});
td[contenteditable="true"]:focus {
    background-color: yellow;
}

.orange{
  background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <td contenteditable="true" >"Stuff"</td>
</table>

Here is a fiddle to play with: https://jsfiddle.net/8zbrxwpz/

Upvotes: 1

bhansa
bhansa

Reputation: 7514

Use td[contenteditable="true"] selector, and add the table parent as well.

td[contenteditable="true"]:focus {
    background-color: yellow;
}
  <table>
  <td contenteditable="true" >"Stuff"</td>
  </table>

https://jsfiddle.net/kasyzytr/

Upvotes: 0

Related Questions