Skip to content

Instantly share code, notes, and snippets.

@dmitru
Created April 29, 2017 08:09
Show Gist options
  • Save dmitru/0b6ee50eddcc60514b19268a852a9d31 to your computer and use it in GitHub Desktop.
Save dmitru/0b6ee50eddcc60514b19268a852a9d31 to your computer and use it in GitHub Desktop.
'use strict';
(function () {
var pinHandle = document.querySelector('.pin__main');
var formAddress = document.querySelector('#address');
var PIN_HEIGHT = 94;
var PIN_WIDTH = 74;
var tokyoMap = document.querySelector('.tokyo');
var MIN_X = 0;
var MAX_X = 1200;
var MIN_Y = 180;
var MAX_Y = 665;
pinHandle.addEventListener('mousedown', function onPinMouseDown(evt) {
evt.preventDefault();
var startCoords = {
x: evt.clientX,
y: evt.clientY
};
function onMouseMove(moveEvt) {
moveEvt.preventDefault();
var shift = {
x: startCoords.x - moveEvt.clientX,
y: startCoords.y - moveEvt.clientY
};
startCoords = {
x: moveEvt.clientX,
y: moveEvt.clientY
};
var pinTop = pinHandle.offsetTop + PIN_HEIGHT;
var pinLeft = pinHandle.offsetLeft + PIN_WIDTH / 2;
if (pinTop >= MIN_Y && pinTop <= MAX_Y && pinLeft >= MIN_X && pinLeft <= MAX_X) {
pinHandle.style.top = (pinHandle.offsetTop - shift.y) + 'px';
pinHandle.style.left = (pinHandle.offsetLeft - shift.x) + 'px';
} else if (pinTop < MIN_Y) {
pinHandle.style.top = MIN_Y - PIN_HEIGHT + 'px';
} else if (pinTop > MAX_Y) {
pinHandle.style.top = MAX_Y - PIN_HEIGHT + 'px';
} else if (pinLeft < MIN_X) {
pinHandle.style.left = MIN_X - PIN_WIDTH / 2 + 'px';
} else if (pinLeft > MAX_X) {
pinHandle.style.left = MAX_X - PIN_WIDTH / 2 + 'px';
}
formAddress.value = 'x: ' + pinLeft + ' y: ' + pinTop;
}
function onMouseUp(upEvt) {
upEvt.preventDefault();
tokyoMap.removeEventListener('mousemove', onMouseMove);
tokyoMap.removeEventListener('mouseup', onMouseUp);
}
tokyoMap.addEventListener('mousemove', onMouseMove);
tokyoMap.addEventListener('mouseup', onMouseUp);
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment