Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Difference between event.clientX and e.offsetX?

I was practicing something I saw on Code Pen where you could move the mouse to change the color of the page. I coded the first block myself based on research I did online for how to find coordinates of your mouse and convert them to RGB. The second block of code is how to original author did it. Theirs is much faster and smoother when mousing over the page. Why the different in performance?

// slower clunky change of color
window.onload = function(){
  var moveChange = document.getElementById("colorChange");
  moveChange.onmouseover = function() {
    var x = event.clientX;
    var y = event.clientY;
    document.body.style.backgroundColor = 'rgb(' + x + ', 180,' + y + ')';
  };
}


// much faster and seamless change of color
window.onload = function() {
  var moveChange= document.getElementById("colorChange");
  moveChange.addEventListener("mousemove", runEvent);

  function runEvent(e) {
    e.preventDefault();
    document.body.style.backgroundColor = 'rgb(' + e.offsetX + ', 180,' + e.offsetY + ')';
  }
}

1 Answer

You seem to be convinced that the difference between event.clientX and e.offsetX is responsible but that isn't the only difference between the two. You are attaching the handler to two different events, mouseover and mousemove, and they don't behave the same. mouseover will only trigger once when the mouse enters the element's boundaries and won't retrigger until the mouse exits and reenters it. mousemove on the other hand will report continuously as the mouse moves across the element's region.