Categories
JavaScript Answers

How to Loop Through All DOM Elements on a Page with JavaScript?

Sometimes we want to loop through all DOM elements on a page with JavaScript.

In this article, we’ll look at how to loop through all DOM elements on a page with JavaScript.

Select All Elements with document.getElementsByTagName

We can select all elements on a page with the document.getElementsByTagName method.

For instance, if we have the following HTML:

<div>
  <span>hello world</span>
</div>
<p>
  how are you
</p>

Then we can loop through all of them by writing:

const allEls = document.getElementsByTagName("*");
for (const el of allEls) {
  console.log(el)
}

We select all elements by calling document.getElementsByTagName with '*' .

And then we can loop through all the returned elements with the for-of loop.

Select All Elements with document.querySelectorAll

We can select all elements on a page with the document.querySelectorAll method.

For instance, if we have the following HTML:

<div>
  <span>hello world</span>
</div>
<p>
  how are you
</p>

Then we can loop through all of them by writing:

const allEls = document.querySelectorAll("*");
for (const el of allEls) {
  console.log(el)
}

We select all elements by calling document.querySelectorAll with '*' .

And then we can loop through all the returned elements with the for-of loop.

Conclusion

We can use the document.getElementsByTagName or document.querySelectorAll method to get all elements on a page.

Then we can loop through them all with the for-of loop.

Categories
JavaScript Answers

How to Handle Right Clicks with JavaScript?

Sometimes, we want to do something when a user right-clicks on an element in our web app.

In this article, we’ll look at how to handle right-clicks with JavaScript.

Set the window.oncontextmenu Property to a Function

We can set the window.contextmenu property to an event handler function to listen for right clicks on the page.

To do this, we write:

window.oncontextmenu = (e) => {  
  e.preventDefault()  
  console.log('right clicked')  
}

We have the e parameter that has the right-click event object.

We call e.preventDefault to stop the default behavior for right clicks, which is to show the context menu on the page.

Once we called that, we can do anything we want in the rest of the function when the user right-clicks on the page.

Call the window.addEventListener Method to Add an Event Listener Function

Another way to do something when we right-click on the page is to call the window.addEventListener method to add an event listener function for listening to right clicks.

For instance, we can write:

window.addEventListener('contextmenu', (ev) => {  
  ev.preventDefault();  
  console.log('right clicked')  
});

We pass in the 'contextmenu' string to listen for context menu click events.

Then in the event listener, we call preventDefault the same way to stop the default right-click menu from displaying.

And then we can do what we want when the user right-clicks on the page.

Conclusion

We can listen for the contextmenu event and call preventDefault in the event handler function to run our own JavaScript when we right-click on the page.

Categories
JavaScript Answers

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

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

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

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 with JavaScript?

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

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

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 Add a Widget that we can Zoom In and Out on a Web Page When We Spin the Mouse Wheel Like on Google Maps with JavaScript?

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.