Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript event when mouseover AND mousedown

Tags:

javascript

Using only Javascript (no jQuery etc) , is there a way I can trigger an event if those two conditions are met?

I currently have a n x m table and I can change the color of each entry with a click. However, I also want to be able to drag the mouse around instead of having to click many times. Is this possible?

This is what I have:

<div id ="startButton">
  <button onclick="startGame()">START</button>
</div>
(...)
var tableEntry = document.getElementsByTagName('td');

(...)
function startGame() {
  for(var i = 0, il=tableEntry.length; i < il; i++) {
    tableEntry[i].onmousedown = toggle; //changes color 
  }
}
like image 241
Mil3d Avatar asked Aug 22 '26 13:08

Mil3d


2 Answers

Since events in JS are "short-lived", you'd have to maintain some shared state variable.

var table = document.getElementById('game-table');
var tableEntry = table.getElementsByTagName('td');
var isToggling = false;

function enableToggle(e) {
  console.log('enableToggle')
  isToggling = true;

  if (e.target !== table) {
    toggle(e);
  }
}

function disableToggle() {
  console.log('disableToggle')
  isToggling = false;
}

function toggle(e) {
  if (isToggling === false) {
    return;
  }

  console.log('toggle:', e.target);

  e.target.classList.toggle('active');
}

function startGame() {
  table.onmousedown = enableToggle;

  for (var i = 0, il = tableEntry.length; i < il; i++) {
    tableEntry[i].onmouseenter = toggle; //changes color 
  }

  table.onmouseup = disableToggle;
}

startGame();
table,
td {
  background: rgba(0, 0, 0, 0.4);
  padding: 20px;
  color: white;
  user-select: none;
}

td.active {
  color: red;
}
<table id="game-table">
  <tr>
    <td>1-1</td>
    <td>1-2</td>
    <td>1-3</td>
  </tr>

  <tr>
    <td>2-1</td>
    <td>2-2</td>
    <td>2-3</td>
  </tr>

  <tr>
    <td>3-1</td>
    <td>3-2</td>
    <td>3-3</td>
  </tr>
</table>
like image 169
zhirzh Avatar answered Aug 25 '26 03:08

zhirzh


Set a variable in your onmousedown, and clear it in your onmouseup.

Then, in your onmousemove, check the variable. If it's set the mouse is down, if not it's up.

You will have to get a bit creative. What you are describing is a drag event. To avoid the default drag behaviour you will need to respond to the ondragstart event and return false after calling event.preventDefault();

like image 27
allnodcoms Avatar answered Aug 25 '26 04:08

allnodcoms