3

I'm trying to create a real-time drawing tool to help reinforce my JavaScript and node.js skills. I am having a problem with just the JavaScript part. On a 3 by 3 grid, I want it so if you have the mouse down and go over multiple divs, in other words click and drag, the other divs will also change color.

However, right now only the first div that I mousedown on will actually change color.

If you visit my jsfiddle, http://jsfiddle.net/a5j8u6wq/

try onmousedown over multiple boxes, and you will see it fails to colorize boxes other than the first one.

How do I fix this?

Thanks

A copy of what is on jsfiddle is included below:

HTML

  <body>
<div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
</div>
  </body>

CSS

    div {
    width: 300px;
    height: 600px;
}

div div {
    width: 100px;
    height: 100px;
    outline: 1px solid;
    float: left;
}

JavaScript

    var box;
    var boxArray;
             boxArray = [];

        box = document.getElementsByClassName("box");
        for ( var i = 0; i < box.length; i++ ) (function(i){
  box[i].onmousedown = function() {
    box[i].style.backgroundColor = "green";
  }
})(i);
clarity123
  • 1,956
  • 10
  • 16
mre12345
  • 1,087
  • 4
  • 16
  • 23

1 Answers1

4

The onmousedown event will only capture when you press the mouse button down on the box. It's check if you pressed the mouse button down on that item, and not checking is the mouse currently down on the item. So it will only effect the box you clicked. You are looking for onmousemove or onmouseenter, then in the event check if the left mouse button is down, in this case meaning that e.buttons is 1:

box[i].onmousemove = function(e) {
    if(e.buttons == 1) // If the mouse button is down
        box[i].style.backgroundColor = "green"; // draw
}

Fiddle Example

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54