Select mouse

by Lazaro Contreras

CSS

html {
  background: url('/img/logo.png');
}

.select {
  position: fixed;
  display: block;
  margin: 0;
  background: rgba(0, 116, 217, 0.4);
  border: 1px solid #0563b5;
  cursor: default;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

JavaScript

var select, x, y;
window.onmousedown = function(e) {
  select = document.createElement('div');
  document.body.appendChild(select);
  x = e.clientX;
  y = e.clientY;
  select.className = 'select';
  select.style.top = y + 'px';
  select.style.left = x + 'px';
  window.addEventListener('mousemove', selectOn);
  window.addEventListener('mouseup', selectOff);
}

function selectOn(e) {
  if (e.clientX > x) {
    select.style.width = e.clientX - x + 'px';
  } else {
		select.style.left = e.clientX + 'px';
    select.style.width = x - e.clientX + 'px';
  }
  if (e.clientY > y) {
    select.style.height = e.clientY - y + 'px';
  } else {
  	select.style.top = e.clientY + 'px';
    select.style.height = y - e.clientY + 'px';
  }
}

function selectOff() {
  select.remove();
  window.removeEventListener('mousemove', selectOn);
  window.removeEventListener('mouseup', selectOff);
}