Categories
JavaScript Answers

How to determine if an HTML element’s content overflows with JavaScript?

To determine if an HTML element’s content overflows with JavaScript, we check if the parent width is smaller than the element’s width.

For instance, we write

const checkOverflow = (elem) => {
  const elemWidth = elem.getBoundingClientRect().width;
  const parentWidth = elem.parentElement.getBoundingClientRect().width;

  return elemWidth > parentWidth;
};

to get the elem element’s width with elem.getBoundingClientRect().width;.

We get its parent’s width with elem.parentElement.getBoundingClientRect().width;.

And then if elem‘s width is bigger than parentWidth, then elem overflows its parent.

Categories
JavaScript Answers

How to remove whitespaces inside a string in JavaScript?

To remove whitespaces inside a string in JavaScript, we call the string replace method.

For instance, we write

const s = "hello world".replace(/\s/g, "");

to call "hello world".replace to replace all spaces with empty strings.

\s matches spaces.

And the g flag makes replace replace all spaces.

Categories
JavaScript Answers

How to get list of data-* attributes using JavaScript?

To get list of data-* attributes using JavaScript, we use the dataset property.

For instance, we write

const attributes = element.dataset;
const cat = element.dataset.cat;

to get a list of data- attributes as an object with the element.dataset property.

We use the element.dataset.cat property to get the value of the element‘s data-cat attribute.

Categories
JavaScript Answers

How to make anchor link go some pixels above where it’s linked to with JavaScript?

To make anchor link go some pixels above where it’s linked to with JavaScript, we call scrollTo when the URL hash changes.

For instance, we write

window.addEventListener("hashchange", () => {
  window.scrollTo(window.scrollX, window.scrollY - 100);
});

to listen for the hashchange event on the window with addEventListener.

In the hashchange listener, we call scrollTo to scroll to the scroll position of the window.

window.scrollX and window.scrollY has the x and y coordinates of the scroll position.

The hashchange event is emitted, when the URL part after the # sign changes.

Categories
JavaScript Answers

How to add a simple onClick event handler to a canvas element with JavaScript?

To add a simple onClick event handler to a canvas element with JavaScript, we set the canvas’ onclick property to the click handler.

For instance, we write

const elem = document.getElementById("myCanvas");
elem.onclick = () => {
  console.log("hello world");
};

to select the canvas with getElementById.

And then we set its onclick property to a function that logs 'hello world'.

As a result, when we click on the canvas, we see 'hello world'. logged.