Reputation: 10675
I'm trying to write an event listener that moves an element where I move my mouse, by setting properties of the CSSStyleDeclaration object on the element:
var overlay = document.getElementById('overlay');
document.body.addEventListener('mousemove',function moveOverlay(evt){
overlay.style.left = evt.clientX;
overlay.style.top = evt.clientY;
});
However, after each assignment to a property of style
runs, the value (as checked in the debugger) doesn't change - it remains the default empty string value ''
. A change like overlay.style.color = 'blue'
works - what am I doing wrong?
Upvotes: 0
Views: 162
Reputation: 10675
CSS style rules will only be assigned as a property value if they are syntactically valid - if the prospective value is invalid for the CSS rule in question, the operation will be ignored. Numbers for CSS properties need a unit suffix to be valid - in this case, it needs to be specified that the positions are in pixels. Try evt.clientX + 'px'
instead.
Upvotes: 2