3

In the code example, clicking on both divs makes the background color gray.

Clicking a second time on the first div (content editable) changes the color back to white. Clicking the second div (not content editable) does not.

Is there a way to easily achieve the same result for the second div?

<div contenteditable="true" style="width:100px; height:100px; border: 1px solid red;" onclick="this.style.backgroundColor='gray'" onblur="this.style.backgroundColor='white'"></div>

<div style="width:100px; height:100px; border: 1px solid blue;" onclick="this.style.backgroundColor='gray'" onblur="this.style.backgroundColor='white'"></div> 

https://jsfiddle.net/2u3e0d1v/

Daniel Williams
  • 2,195
  • 7
  • 32
  • 53
  • I would check if the clicked element was the div or not... here a similar situation: http://stackoverflow.com/a/7385673/2126792 – pschueller Feb 23 '15 at 01:40
  • I've ended up adding an event listener to the document body that will change the background color onmousedown. Thanks for your post. – Daniel Williams Feb 23 '15 at 01:55

1 Answers1

0

I am not sure if there is a way to exactly simulate onblur... I would use a jQuery function similar to this one here.

So for example:

$(document).mouseup(function (e)
  {
      var container = $(".noteditable");
 
      if (!container.is(e.target) // if the target of the click isn't the container...
          && container.has(e.target).length === 0) // ... nor a descendant of the container
      {
          container.css('background-color', 'white');
      }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contenteditable="true" style="width:100px; height:100px; border: 1px solid red;" onclick="this.style.backgroundColor='gray'" onblur="this.style.backgroundColor='white'"></div>

<div class="noteditable" style="width:100px; height:100px; border: 1px solid blue;" onclick="this.style.backgroundColor='gray'"></div>

Or in pure JS something similar to this:

function resetBg(){
    if(window.event.srcElement.id != 'noteditable'){
        document.getElementById('noteditable').style.backgroundColor = 'white';
    }
}

document.onclick = resetBg;
<div contenteditable="true" style="width:100px; height:100px; border: 1px solid red;" onclick="this.style.backgroundColor='gray'" onblur="this.style.backgroundColor='white'"></div>

<div id="noteditable" style="width:100px; height:100px; border: 1px solid blue;" onclick="this.style.backgroundColor='gray'"></div>
Community
  • 1
  • 1
pschueller
  • 4,362
  • 2
  • 27
  • 50
  • I've ended up adding an event listener to the document body that will change the background color onmousedown. Thanks for your post. – Daniel Williams Feb 23 '15 at 01:54