Categories
JavaScript Answers

How to Get the Coordinates of a Mouse Click on a Canvas Element?

Sometimes, we may want to get the coordinates of a mouse on an HTML canvas element.

In this article, we’ll look at how to get the coordinates of a mouse click on a canvas element.

Add a mousedown Event Handler

We can get the coordinates of a mouse click from the event object we get from the mousedown event handler.

For instance, we can write the following HTML:

<canvas style="width: 200px; height: 100px">
</canvas>

Then we can write the following JavaScript code:

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();

const getCursorPosition = (canvas, event) => {
  const rect = canvas.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top
  console.log(x, y)
}

canvas.addEventListener('mousedown', (e) => {
  getCursorPosition(canvas, e)
})

We add a canvas element with width 200px and height 100px.

Then we get the canvas element with the document.querySelector method.

Then we get the canvas context with the getContext method.

And then we call moveTo to move the cursor to the given x, y coordinates.

And we call lineTo to draw a line to the given x, y coordinates.

Then we call stroke to draw the line.

Next, we create the getCursorPosition function to get the canvas and event parameters.

We call canvas.getBoundingClientRect to get the rect object, which has the left and top properties to get the x and y coordinates of the top-left corner.

Then we subtract that from the event.clientX and event.clientY properties that have the mouse coordinates of the screen that we clicked on.

Therefore, x and y has the mouse coordinates we clicked on on the canvas.

Finally, we call canvas.addEventListener to add the mousedown event listener.

In it, we call getCursorPosition to get the mouse coordinates we clicked on on the canvas and log it.

x and y are in pixels.

Also, we can get the offsetX and offsetY properties from the event object to get the coordinates of the canvas we clicked on.

For instance, we can write:

const canvas = document.querySelector('canvas')
const ctx = canvas.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();

const getCursorPosition = (canvas, event) => {
  const x = event.offsetX
  const y = event.offsetY
  console.log(x, y)
}

canvas.addEventListener('mousedown', (e) => {
  getCursorPosition(canvas, e)
})

to get the mouse coordinates without doing the calculations.

Conclusion

We can get the mouse coordinates of the location we clicked on on the canvas with a few properties from the mousedown event object.

Categories
JavaScript Answers

How to Find the Width of an Element Using Vanilla JavaScript?

Sometimes, we want to find the width of an element with vanilla JavaScript.

In this article, we’ll look at how to find the width of an element with vanilla JavaScript.

HTMLElement.offsetWidth

One property we can use to find the width of an element is the offsetWidth property.

It’s a read-only property that returned the layout width of an element as an integer.

It’s measured in pixels of the element’s CSS width, including borders, padding, and vertical scrollbars if it’s rendered.

And it doesn’t include the width of any pseudo-elements.

If the element is hidden, then 0 is returned.

For instance, we can write the following HTML:

<p>  
  hello world  
</p>

Then we can get the offsetWidth by writing:

const p = document.querySelector('p');  
console.log(p.offsetWidth)

HTMLElement.clientWidth

Another property we can use to get the width of an element is the clientWidth property.

It’s zero for inline elements and elements with no CSS.

Otherwise, it’s the inner width of an element in pixels.

It includes padding but excludes borders, margins, and vertical scrollbars if present.

For instance, we can write the following HTML:

<p>  
  hello world  
</p>

Then we can get the offsetWidth by writing:

const p = document.querySelector('p');  
console.log(p.clientWidth)

to get the clientWidth property.

Using the getComputedStyle Function

The getComputedStyle global function returns an object containing the values of all CSS properties of an element after the active stylesheets and basic computations are applied to it.

We can access the individual CSS properties from the returned object.

The width property would have the computed width of an element after the stylesheets, changes in width with JavaScript, etc. are applied to it.

For instance, we can write:

const p = document.querySelector('p');  
console.log(getComputedStyle(p).width)

Then we get the width of the p element with the unit as a string.

Conclusion

There’re various properties and methods we can use to get the width of an element with vanilla JavaScript.

Categories
JavaScript Answers

How to Select All Elements with a “data-*” Attribute With Vanilla JavaScript?

We can use data- attributes to store data in our HTML elements.

Therefore, we may want to get these elements and use them.

In this article, we’ll look at how to select all elements with a data- attribute with vanilla JavaScript.

Select All Elements with a “data-*” Attribute With Vanilla JavaScript

We can select all elements with a data- attribute with the document.querySelectorAll method.

For instance, we can write the following HTML:

<p data-foo='1'>
  1
</p>
<p data-foo='2'>
  2
</p>

Then we can select all the elements with the data-foo attribute by writing:

const dataFoo = document.querySelectorAll('[data-foo]');
console.log(dataFoo)

To select the elements with the data-foo attribute set to a given value, we can write:

const dataFoo = document.querySelectorAll('[data-foo="1"]');
console.log(dataFoo)

Then we get the data-foo attribute with the value set to 1.

To get the value attribute value from the element object, we can use the dataset property.

For instance, we can write:

const dataFoo = document.querySelector('[data-foo="1"]');
console.log(dataFoo.dataset.foo)

to select the element with the data-foo attribute set to 1 with document.querySelector .

Then we use dataFoo.dataset.foo to get the value of the data-foo attribute from the selected element.

The dataFoo.dataset.foo property is also a setter, so we can write:

const dataFoo = document.querySelector('[data-foo="1"]');
dataFoo.dataset.foo = 3

to replace the data-foo attribute value of 1 with 3.

Conclusion

We can select all elements with the given data- attribute set with the document.querySelectorAll method with the given selector.

Categories
JavaScript Answers

How to Remove Time from a Date with Moment.js?

Sometimes, we want to remove the time portion of a date from the date in our JavaScript app.

We can do this easily with the moment.js library.

In this article, we’ll look at how to remove the time portion of a date with moment.js.

The startOf Method

We can remove the time portion from a date with the startOf method.

For instance, we can write:

const day = moment(new Date(2021, 1, 1, 1, 1)).startOf('day')  
console.log(day.toDate())

We pass in a date with the hour and minutes set into the moment function.

Then we call startOf with the 'day' argument to get return a moment object with the time set to midnight of the same date.

Then we call toDate to convert it back to a native JavaScript date.

And so we get:

Mon Feb 01 2021 00:00:00 GMT-0800 (Pacific Standard Time)

as the result if our device’s time is in the Pacific time zone.

The format Method

The format method lets us format a date the way we want.

We can pass in the 'LL' formatting code to return a date string with only the date portion of a date.

For instance, we can write:

const day = moment(new Date(2021, 1, 1, 1, 1)).format('LL')  
console.log(day)

We create the moment object the same way.

But after that, we call format with the 'LL' formatting code.

Then day would be the following date string:

'February 1, 2021'

Also, we can pass in 'L' to get the date string in MM/DD/YYYY format.

So we can write:

const day = moment(new Date(2021, 1, 1, 1, 1)).format('L')  
console.log(day)

And we get:

'02/01/2021'

as the value of day .

We can also use MM to get the 2 digit month. DD gets the 2 digit day. And YYYY gets the 4 digit year.

So we can write:

const day = moment(new Date(2021, 1, 1, 1, 1)).format('MM/DD/YYYY')  
console.log(day)

to get the same result as with 'L' .

MMMM gets the full month name, D gets the day number without the leading zero padding.

So we can write:

const day = moment(new Date(2021, 1, 1, 1, 1)).format('MMMM D, YYYY')  
console.log(day)

to get the same date string as 'LL' .

Conclusion

We can use the startOf method to return a moment date object without the time portion of a date.

Also, we can use the format method to return a date string without the time portion of a date.

Categories
JavaScript Answers

How to Clear All Cookies with JavaScript?

Sometimes, we may clear all the cookies stored in the browser for the given site.

In this article, we’ll look at how to clear all cookies with JavaScript.

Setting the Expiry Date of All Cookies to a Date Earlier than the Current Date-Time

We can clear all cookies with JavaScript by setting the expiry date of each cookie to a date and time that’s earlier than the current time.

To do this, we write:

const deleteAllCookies = () => {
  const cookies = document.cookie.split(";");

  for (const cookie of cookies) {
    const eqPos = cookie.indexOf("=");
    const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
  }
}

deleteAllCookies()

We create the deleteAllCookies function that splits the document.cookie string.

Then we loop through each cookie within the cookies array.

And then we get the index of the = sign and remove the equal sign if it’s not there.

Then we add the expires=Thu, 01 Jan 1970 00:00:00 GMT string after it to remove the cookie by making it expire.

This won’t delete cookies with the HttpOnly flag set since the flag disables JavaScript’s access to the cookie.

It also won’t delete cookies that have a Path value set.

This is because we can’t delete it without specifying the same Path value with which it’s set.

Conclusion

We can clear some cookies from the browser by splitting the cookie string and then adding an expiry date to it that’s earlier than the current date and time.