Categories
JavaScript Answers

How to scroll an HTML page to a given anchor with JavaScript?

To scroll an HTML page to a given anchor with JavaScript, we set the location.hash property.

For instance, we write

const scrollTo = (hash) => {
  location.hash = "#" + hash;
};

to define the scrollTo function.

In it, we set location.hash to the selector for the ID for the element we want to scroll to.

Categories
JavaScript Answers

How to wait for the end of ‘resize’ event and only then perform an action with JavaScript?

To wait for the end of ‘resize’ event and only then perform an action with JavaScript, we set the window.onresize property to the resize event handler.

For instance, we write

window.onresize = () => {
  console.log("resized");
};

to set window.onresize to a function that’s called when we resize the tab or window.

Categories
JavaScript Answers

How to show the “Are you sure you want to navigate away from this page?” message when changes committed with JavaScript?

To show the "Are you sure you want to navigate away from this page?" message when changes committed with JavaScript, we set the window.onbeforeunload property to a function that returns a truthy value.

For instance, we write

window.onbeforeunload = () => {
  return true;
};

to set window.onbeforeunload to a function that returns true to show the "Are you sure you want to navigate away from this page?" message before the tab or window is closed or navigation starts.

Categories
JavaScript Answers

How to programmatically change the src of an img tag with JavaScript?

To programmatically change the src of an img tag with JavaScript, we set the src property of the img element.

For instance, we write

document.getElementById("imageid").src = "../template/save.png";

to select the img element with getElementById.

Then we set its src property to the path string or URL of the image.

Categories
React Answers

How to render HTML string as real HTML with React?

To render HTML string as real HTML with React, we use the dangerouslySetInnerHTML prop.

For instance, we write

<div dangerouslySetInnerHTML={{ __html: htmlString }} />;

to add a div with the dangerouslySetInnerHTML prop set to an object with the __html property set to the htmlString string.

Then htmlString is rendered as HTML.