Been thinking about this for many hours now but can't come up with a solution. I have about 5 divs with the same class: <div contenteditable="true" class="change">
When I click on a div, the first function makes the background color white. When I leave the div, I want the color to change depending on what I wrote inside the div.
The good thing is that the color changes. The bad thing is that when I afterwards click other divs and leave them, they receive the same color as the first div. Doesn't matter if I write nothing or if I write "yes", "no" or "maybe", the following divs still get the same color as first div when I leave them
Help! :(
$(".change").focus(function() {
var message = document.querySelector(".change").innerHTML;
this.style.backgroundColor=("white");
});
$((".change") ).focusout(function() {
var message = document.querySelector(".change").innerHTML;
console.log(message);
switch (message) {
case 'yes':
this.style.backgroundColor=("green");
break;
case 'no':
this.style.backgroundColor=("red");
break;
case 'maybe':
this.style.backgroundColor=("yellow");
break;
default:
this.style.backgroundColor=("white");
break;
}
});
Just change the var message = document.querySelector(".change").innerHTML; to var message = $(this).text();
$(".change").focus(function() {
var message = document.querySelector(".change").innerHTML;
this.style.backgroundColor=("white");
});
$((".change") ).focusout(function() {
var message = $(this).text();
switch (message) {
case 'yes':
this.style.backgroundColor=("green");
break;
case 'no':
this.style.backgroundColor=("red");
break;
case 'maybe':
this.style.backgroundColor=("yellow");
break;
default:
this.style.backgroundColor=("white");
break;
}
})
div {
border: 1px solid black;
}
body {
background: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true" class="change"></div>
<br />
<div contenteditable="true" class="change"></div>
<br />
<div contenteditable="true" class="change"></div>
<br />
<div contenteditable="true" class="change"></div>
<br />
<div contenteditable="true" class="change"></div>
<br />