Home > Mobile >  event listener that fires only when mousedown && mouseover are true
event listener that fires only when mousedown && mouseover are true

Time:04-09

I have found many similar questions and answers like mine. Unfortunatly, I have tried to adapt those answers to fit my problem but I cannot make it work. I am making a drawing pad application. The drawing pad is made of a container full of divs. I want the color to change only when mousedown and mouseover are both true. basically, I want to click and drag my drawing lines. Im probably way out to lunch here but I am at my whits end trying things.

let boxes = document.getElementsByClassName("grid-item");
let isClicked = false;
let isHover = false;

for (box of boxes) {
  box.addEventListener("mousedown", () => isClicked = true);
}
for (box of boxes) {
  box.addEventListener("mouseover", () => isHover = true);
}

function draw() {
  if (isClicked == true && isHover == true) {
    box.target.style.background_color = "black";
  }
}

CodePudding user response:

Instead of trying to manage and track global variables, you can use the event object passed. In my example, I have a function which can make the event target black, by changing the background color. I did use the style.backgroundColor because style.background-color is incorrect for js. If the mousedown event is triggered, you can safely assume the cursor is over the element. The mouseover event does not always make the target black. Instead, I check the event property .buttons which will be 1 if the left mousebutton is pressed, and 0 if not. This way, I can verify if it is clicked, then we just pass the event along to our make black function.

It is possible to solve this problem by tracking global variables, however you would need to be doing a lot of "state managing" which can quickly become messy and complex. You would need a mouseout function that turns the isHover off, as well as a mouseup function that turns the isClick off. You would probably need some debouncing in case the mouseout or mouseup event didn't trigger due to a right click or the cursor being in a different position. Then you would also need to track which element isHover and isClick which is redundant in this case because we can just check the event object from our mouseover event.

const boxes = [...document.getElementsByClassName("grid-item")];
const makeBlack = event => event.target.style.backgroundColor = "black";
function equip(box) {
  box.addEventListener("mousedown", makeBlack);
  box.addEventListener("mouseover", event => {
    if (event.buttons == 1) makeBlack(event);
  });
}
boxes.forEach(equip);

  • Related