Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yCodeTech/4e77ed49fb2dad292a2d3466ff51b98e to your computer and use it in GitHub Desktop.
Save yCodeTech/4e77ed49fb2dad292a2d3466ff51b98e to your computer and use it in GitHub Desktop.

A mousemove utility to get the x coordinate of an element or the window. Coordinates are left-based, but we might want to get the x coordinates originating from the right instead. To do this we need to do a bit of maths.

This little function utility (using jQuery) logs to the console the x-left and x-right coordinates.

Example on Codepen.

function mouseXCoords(element) {
	var obj = {
		"x-left": 0,
		"x-right": 0,
	};

	$(element).on("mousemove", function (event) {
		var $element = $(element);
		var winWidth = $(window).width();

		if (element === window) {
			// X-left -- x coordinate originating from the left of the window (default behaviour).
			obj["x-left"] = event.pageX;

			// X-right -- x coordinate originating from the right of the window
			// (window width minus the x-left coordinate).
			obj["x-right"] = winWidth - event.pageX;
		} else {
			var offset = $element.offset(),
				elWidth = $element.width();

			obj["x-left"] = event.pageX - offset.left + 1;
			obj["x-right"] = elWidth - (event.pageX - offset.left);
		}

		obj["x-left"] = Math.floor(obj["x-left"]);
		obj["x-right"] = Math.floor(obj["x-right"]);

		console.log(obj);
	});
}

/* Usage:
 * For window, specify window without quotes.
 * For every other selector, specify with quotes.
 */
mouseXCoords(window);
mouseXCoords("div");
mouseXCoords(".example");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment