Categories
JavaScript Answers

How to Parse a URL into the Hostname and Path in JavaScript?

Sometimes, we want to parse a URL into the hostname and path parts with JavaScript.

In this article, we’ll look at how to parse a URL into the hostname and path parts with JavaScript.

Create an a Element

We can create an a element and set the href property of it to the URL we want to parse,

Then we can get the properties of it to get the parts we want.

For instance, we can write:

const parser = document.createElement('a');
parser.href = "http://example.com:3000/pathname/?search=foo#hash";

console.log(parser.protocol)
console.log(parser.host)
console.log(parser.hostname)
console.log(parser.port)
console.log(parser.pathname)
console.log(parser.hash)
console.log(parser.search)
console.log(parser.origin)

protocol has the protocol, which is 'http:' .

host is the hostname and the port, which is 'example.com:3000' .

hostname is the hostname, which is 'example.com' .

port is the port, which is 3000.

pathname has the pathname, which is the path after the host, which is '/pathname/' .

hash has the hash, which is #hash .

search has the query string with the question mark before it, which is '?search=foo' .

origin has the protocol and host together, which is ‘ http://example.com:3000’ .

URL Constructor

The URL constructor lets us parse the parts of a URL without creating an a element.

For instance, we can write:

const url= new URL("http://example.com:3000/pathname/?search=foo#hash")

console.log(url.protocol)
console.log(url.host)
console.log(url.hostname)
console.log(url.port)
console.log(url.pathname)
console.log(url.hash)
console.log(url.search)
console.log(url.origin)

We pass the URL into the URL constructor, and we get the same results as before.

The URL constructor is available with most modern browsers.

Conclusion

To parse a URL with JavaScript, we can create an a element and set its href property.

Or we can pass the URL into the URL constructor to get the same result.

Categories
JavaScript Answers

How to Resize HTML5 Canvas to Fit the Window?

Sometimes, we may want to resize an HTML5 canvas to fit the window that it’s in.

In this article, we’ll look at how to resize an HTML5 canvas to fit the window.

Setting the width and height Properties of the Canvas

We can just set the width and height properties of the canvas as the window resizes to set the width and height of the canvas to change its size.

For instance, we can write:

const draw = (canvas) => {
  const ctx = canvas.getContext("2d");
  ctx.beginPath();
  ctx.arc(95, 50, 40, 0, 2 * Math.PI);
  ctx.stroke();
}

const canvas = document.querySelector("canvas");
canvas.width = window.innerWidth
canvas.height = window.innerHeight
draw(canvas)

window.addEventListener('resize', () => {
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight
  draw(canvas)
})

to change the size of the canvas initialize to the window’s dimensions with:

canvas.width = window.innerWidth
canvas.height = window.innerHeight

And we do the same thing in the resize event listener, which we added with the addEventListener method.

When the canvas resizes the content disappears, so they have to be drawn again whenever we resize the canvas by setting the width and height properties.

Set the Size with CSS

We can also set the size of the canvas with CSS to make it fill the screen.

For instance, we can write the following HTML:

<canvas></canvas>

And the following CSS:

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
}

canvas {
  background-color: #ccc;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

to set the canvas’s width and height both to 100%.

We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen.

Also, we make the html and body elements fill the screen by setting the width and height to 100%.

And we can draw on it with:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();

We draw a circle with the arc method.

We have the center x and y coordinates, radius, and start and end angles in radians as arguments in this order.

Conclusion

We can resize the canvas to fit the screen with JavaScript or CSS.

Categories
JavaScript Answers

How to Compare the Date Part of a Date Object Only Without Comparing the Time in JavaScript?

Sometimes, we may want to compare the date part of a date only without comparing the time in our JavaScript app.

In this article, we’ll look at how to compare the date without comparing the time with JavaScript.

Date.prototype.setHours

To compare dates without comparing the time portion, we can set both dates to midnight by using the setHours method that comes with JavaScript date objects.

For instance, we can write:

const date1 = new Date(2021, 1, 1, 1, 1, 1)
date1.setHours(0, 0, 0, 0)

const date2 = new Date(2021, 2, 1)
date2.setHours(0, 0, 0, 0)

console.log(+date2 > +date1)

We call setHours on date1 to set the hours, minutes, and seconds of date1 all to 0.

This will set the date to midnight.

Then we can compare them both without the time part with the > operator as we did in the last line,

To be safe, we convert them both to timestamps first with the + operator.

Therefore, the console log should show true since date2 is ahead of date1 .

To be even safer, we can do both date comparisons after converting them both to UTC date-times.

To do this, we write:

const date1 = new Date(2021, 1, 1, 1, 1, 1)
const date1Copy = new Date(Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate()));
date1Copy.setHours(0, 0, 0, 0)

const date2 = new Date(2021, 2, 1)
const date2Copy = new Date(Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate()));
date2Copy.setHours(0, 0, 0, 0)

console.log(+date2Copy > +date1Copy)

We call Date.UTC with the date parts retrieved from date1 and date2 to create a UTC timestamp.

Then we pass them into the Date constructor to create new date objects.

Then we call setHours on the copied dates and then do the comparison with them.

And we should get the same result from the console log.

Moment.js

The moment.js library has the isAfter method that lets us compare 2 date-times without the time part.

To do this, we write:

const date1 = new Date(2021, 9, 20, 12, 0, 0);
const date2 = new Date(2021, 9, 20, 12, 1, 0);
const isAfter = moment(date2).isAfter(date1, 'day');

console.log(isAfter)

We call isAfter on the moment date object created with the date2 date object.

And we pass in 'day' into the 2nd argument to exclude the time part of each date from the comparison.

Therefore, isAfter should be false as a result since they’re both the same date excluding the time part.

Conclusion

We can use native JavaScript date methods or moment.js to compare dates without the time part.

Categories
JavaScript Answers

How to Get the Hours Difference Between Two Dates with Moment.js?

Moment.js is a popular JavaScript date and time manipulation library that we can use to calculate various things with date and time.

In this library, we’ll look at how to get the hours difference between 2 dates with moment.js

The moment.duration Method

The moment.duration lets us calculate the duration between 2 dates.

We can combine it with the diff method to calculate the hours difference between 2 dates.

For instance, we can write:

const startTime = moment('2021-01-01')  
const end = moment('2021-02-01')  
const duration = moment.duration(end.diff(startTime));  
const hours = duration.asHours();  
console.log(hours)

We call end.diff(startTime) to calculate the difference between end and startTime .

Then we call moment.duration to get the moment duration.

And finally, we call asHours to get the duration as hours.

Therefore, hours is 744 hours.

Moment.js fromNow and from Methods

We can use the fromNow method to get a human readable string of the difference between a date and now.

For instance, we can write:

const diff = moment('2021-01-01').fromNow()   
console.log(diff)

And we get something like ‘2 months ago’ .

We can use moment.js from method to get a human-readable string between the difference between 2 dates.

For instance, we can write:

const a = moment('2021-01-01');  
const b = moment('2021-02-01');  
const diff = a.from(b);  
console.log(diff)

And we get 'a month ago’ as a value of diff since February 1, 2021 is 1 month ahead of January 1, 2021.

Moment.js diff Method with Unit as the Second Argument

We can pass in a second argument to the diff method to return the difference in the unit specified.

For instance, we can write:

const a = moment('2021-01-01');  
const b = moment('2021-02-01');  
const diff = a.diff(b, 'hours');  
console.log(diff)

We get the difference between date-time a and b .

And a is behind b by 1 month, so we get -744 as the result of diff .

The 2nd argument is 'hours' so the result is in hours.

Conclusion

We can get the difference between 2 dates with the units we specified with various moment.js methods.

Also, we can get human readable durations with moment.js.

Categories
JavaScript Answers

How to Simulate a Keypress Event Programmatically with JavaScript?

dispatchEvent Method

We can call the dispatchEvent method to trigger an event of our choice.

For instance, we can write:

window.addEventListener('keydown', (e) => {
  console.log(e)
})

window.dispatchEvent(new KeyboardEvent('keydown', {
  'key': 'a'
}));

to listen to the keydown event and trigger it.

We call addEventListener with 'keydown' to listen to the keydown event.

Then to trigger the keydown event, we call window.dispatchEvent with a KeyboardEvent instance.

We pass in the type of keyboard event to trigger into the first argument of the constructor.

And we pass in an object with the options to set in the event object into the 2nd argument.

Therefore, after dispatchEvent is run, then e.key should be 'a' when logged in the callback.

We can set more options in the object.

For instance, we can write:

window.addEventListener('keydown', (e) => {
  console.log(e)
})

window.dispatchEvent(new KeyboardEvent('keydown', {
  key: "e",
  keyCode: 69,
  code: "KeyE",
  which: 69,
  shiftKey: false,
  ctrlKey: false,
  metaKey: false
}));

to set more options in the object.

keyCode is the numeric code of the key that we want to set.

code has the name of the key.

which has the keyboard key number.

shiftKey sets whether we want to press the shift key in addition to the key we’re pressing.

ctrlKey sets whether we want to press the Ctrl key in addition to the key we’re pressing.

metaKey sets whether we want to press the meta key in addition to the key we’re pressing.

The meta key is the Windows key on PC keyboards and the command key on Mac keyboards.

When the event is triggered, we should see all the options logged in the addEventListener callback.

They should be in the same properties in the e object as in the options object we pass into the KeyboardEvent constructor.

We can write the same code with the keyup event.

We just replace 'keydown' with 'keyup' everywhere.