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.

Categories
HTML

How to select multiple files with file input with HTML?

To select multiple files with file input with HTML, we add the multiple attribute to the file input.

For instance, we write

<input type="file" name="filefield" multiple="multiple" />

to add the multiple attribute to the file input to let us select multiple files from the file selection dialog.

Categories
CSS

How to make Twitter Bootstrap tooltips have multiple lines with CSS?

To make Twitter Bootstrap tooltips have multiple lines with CSS, we set the white-space property.

For instance, we write

.tooltip-inner {
  white-space: pre-wrap;
}

to select the tooltip-inner class and set the white-space property to pre-wrap to wrap the tooltip text.

Categories
JavaScript Answers

How to fix getImageData() error The canvas has been tainted by cross-origin data with JavaScript?

To fix getImageData() error The canvas has been tainted by cross-origin data with JavaScript, we set the img element’s crossOrigin attribute.

For instance, we write

img.crossOrigin = "Anonymous";

to let us load cross origin images in an img element with JavaScript without getting cross origin errors.

This works for servers that has the Access-Control-Allow-Origin header set to '*'.