Categories
JavaScript Answers

How to Convert a Unix Timestamp to a Calendar Date with Moment.js?

Sometimes, we want to convert a Unix timestamp to a calendar date with Moment.js.

In this article, we’ll look at how to convert a Unix timestamp to a calendar dare with moment.js.

Use the unix and format Methods

We can use the unix method to create a moment object from a timestamp.

Then we can use the format method to format the date into a calendar date.

For instance, we can write:

import moment from 'moment'  
const dt = +new Date(2021,1,1)  
const dateString = moment.unix(dt / 1000).format("MM/DD/YYYY");  
console.log(dateString)

We create the dt date object with the Date constructor.

Then we convert it to a timestamp in milliseconds with the unary + operator.

Next, we call moment.unix with a timestamp in seconds.

And then we call format to format the date into MM/DD/YYYY format.

And so dateString is ‘02/01/2021’ .

Use the moment Function and the format Method

We can just use the moment function without the unix method to create a moment object from a timestamp.

For instance, we can write:

import moment from 'moment'  
const dt = +new Date(2021,1,1)  
const dateString = moment(dt).format("MM/DD/YYYY");  
console.log(dateString)

The moment function takes a timestamp in milliseconds.

Therefore, we don’t have to divide dt by 1000 when we pass it in.

The rest of the code is the same and we get the same result as before.

Conclusion

We can convert a timestamp to a calendar date with format with the moment function or the unix method with the format method.

Categories
JavaScript Answers

How to Get the Browser’s Scrollbar Sizes?

Sometimes, we want to get the scrollbar size of an element.

In this article, we’ll look at how to get the size of the scrollbar that’s part of a scrollable element.

Use the getBoundingClientRect Method and the scrollHeight Property

We can get the element’s scrollbar size with the getBoundingClientRect method and the scrollHeight property of an element.

To do this, we subtract the height property value retuned by getBoundingClientRect method by the scrollHeight property’s value to get the width of the horizontal scrollbar.

For instance, if we have:

<div id="app" style='width: 100px; overflow-x: scroll'></div>

Then we can add elements to the div and get the horizontal scrollbar height by writing:

const app = document.querySelector('#app')
for (let i = 0; i < 100; i++) {
  const span = document.createElement('span')
  span.textContent = i
  app.appendChild(span)
}

const getScrollbarHeight = (el) =>{
  return el.getBoundingClientRect().height - el.scrollHeight;
};
console.log(getScrollbarHeight(app))

We get the div with querySelector .

Then we add some spans into the div.

The div has width set and overflow-x set to scroll.

This means the div should have a horizontal scrollbar.

Next, we create the getScrollbarHeight function that subtracts the height from getBoundingClientRect by the scrollHeight , which gives us the height of the horizontal scrollbar.

Then we log the scrollbar height with console log.

Likewise, we can get the scrollbar width with:

<div id="app" style='height: 100px; overflow-y: scroll'></div>

and:

const app = document.querySelector('#app')
for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  app.appendChild(p)
}

const getScrollbarHeight = (el) =>{
  return el.getBoundingClientRect().width - el.scrollWidth;
};
console.log(getScrollbarHeight(app))

We add p elements into a div that’s scrollable vertically.

Instead of subtracting the heights, we subtract the widths.

And we should get the scrollbar width from the console log.

Conclusion

We can get the scrollbar width and height by calling the getBoundingClientRect method and the scroll width or height and getting the difference between the 2.

Categories
JavaScript Answers

How to Clear the Focus of an Active Element with JavaScript?

Sometimes, we want to clear the focus of an active element with JavaScript.

In this article, we’ll look at how to clear the focus of an active element with JavaScript.

Get the Focused Element with the document.activeElement Property

We can get the element that’s in focus with the document.activeElement property.

Then we can call the blur method on it to remove focus from the focused element.

For instance, if we have an input element:

<input>

Then we can prevent users from focusing on it by writing:

document.addEventListener("focus", (e) => {  
  document.activeElement.blur()  
}, true);

We call addEventListener with 'focus' to listen to the focus event on document .

In the event listener, we call document.activeElement.blur to remove focus from the active element, which can be the input.

And we pass in true as the 3rd argument so that the focus event propagates from parent to child instead of the other way around.

This way, we can get the element that’s focused on and call blur on it to remove focus from it.

Conclusion

We can remove focus from an active element with the document.activeElement.blur method.

Categories
JavaScript Answers

How to Add a Widget that we can Zoom In and Out on a Web Page When We Spin the Mouse Wheel Like on Google Maps?

Sometimes, we want to create a widget on a web page where we can zoom in and out on something as we can do on Google Maps.

In this article, we’ll look at how to create a widget that we can zoom in and out with the mouse wheel as we can do on Google Maps.

Draw the Image We can Zoom In and Out on the Canvas

We can draw the image we want to be able to zoom in and out on the canvas.

Then we can listen to the wheel event and transform the canvas image when we move the mouse wheel to let us zoom the image in and out.

For instance, we can write the following HTML:

<canvas id="canvas" width="600" height="200"></canvas>

Then we can write the following JavaScript code to draw the image on the canvas and zoom the image in and out as we move the mouse wheel:

const zoomIntensity = 0.2;

const canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
const width = 600;
const height = 200;

let scale = 1;
let originx = 0;
let originy = 0;
let visibleWidth = width;
let visibleHeight = height;

const draw = () => {
  context.fillStyle = "white";
  context.fillRect(originx, originy, width / scale, height / scale);
  context.fillStyle = "black";
  context.fillRect(50, 50, 100, 100);
  window.requestAnimationFrame(draw);
}
draw();

canvas.onwheel = (event) => {
  event.preventDefault();
  const mousex = event.clientX - canvas.offsetLeft;
  const mousey = event.clientY - canvas.offsetTop;
  const wheel = event.deltaY < 0 ? 1 : -1;
  const zoom = Math.exp(wheel * zoomIntensity);
  context.translate(originx, originy);
  originx -= mousex / (scale * zoom) - mousex / scale;
  originy -= mousey / (scale * zoom) - mousey / scale;
  context.scale(zoom, zoom);
  context.translate(-originx, -originy);
  scale *= zoom;
  visibleWidth = width / scale;
  visibleHeight = height / scale;
}

We have the draw function that clears the screen to white with the first and 2nd lines.

Then we call fillStyle and fillRect to draw a black square.

And then we call window.requestAnimationFrame to redraw the canvas.

Once we defined the draw function, we call it to start the initial draw.

Next, we set the canvas.onwheel property to a function that zoom the image in and out when we move the mouse wheel.

In the function, we first call event.preventDefault() to stop the default behavior when the mouse wheel moves.

Then we get the mouse offset with:

const mousex = event.clientX - canvas.offsetLeft;
const mousey = event.clientY - canvas.offsetTop;

Next, we write the following to normalize mouse movement to avoid unusual jumps:

const wheel = event.deltaY < 0 ? 1 : -1;

Then we get the zoom factor with:

const zoom = Math.exp(wheel * zoomIntensity);

And then we translate the visible origin so that it’s at the context’s origin with:

context.translate(originx, originy);

Then we compute the new origin after the zoom is done with:

originx -= mousex/(scale*zoom) - mousex/scale;
originy -= mousey/(scale*zoom) - mousey/scale;

Next, we call context.scale(zoom, zoom) to scale the image around the origin.

And then we translate the image to offset the visible origin so that it’s at the proper position after zoom:

context.translate(-originx, -originy);

And finally, we update the dimensions after zoom with:

scale *= zoom;
visibleWidth = width / scale;
visibleHeight = height / scale;

Now when we move the mouse wheel, the black square should zoom in and out.

Conclusion

We can add a widget with an image that we can zoom in and out by drawing an image on the canvas and translating and scaling the image when we move the mouse wheel.

Categories
JavaScript Answers

How to Extract the Base URL from a String in JavaScript?

Sometimes, we want to extract the base URL from a string with JavaScript.

In this article, we’ll look at ways to extract the base URL from a string with JavaScript.

Create an Anchor Element and Get the Base URL Parts From the Created Element

We can create an anchor element and get the base URL parts from the created element.

For instance, we can write:

const a = document.createElement("a");
a.href = "http://www.example.com/article/2020/09/14/this-is-an-article/";
const baseUrl = `${a.protocol}//${a.hostname}`
console.log(baseUrl)

We create the a element with document.createElement .

Then we set the href of it to the URL we want to extract the base URL from.

Then we can get the baseURL by combining the protocol and hostname properties.

As a result, we see that baseURL is ‘http://www.example.com’ .

Create a URL Object and Get the Base URL Parts From the Created Element

Another way to get the base URL from a URL is to create an URL instance and extract the base URL parts from the object.

For instance, we can write:

const url = new URL("http://www.example.com/article/2020/09/14/this-is-an-article/")
const baseUrl = `${url.protocol}//${url.hostname}`
console.log(baseUrl)

We pass in the full URL as an argument of the URL constructor.

Then we can get the base URL by combining the protocol and hostname as we did before.

And so baseURL should be the same as the previous example.

Conclusion

We can extract the base URL from a string with JavaScript by creating an anchor element or using the URL constructor.