Categories
JavaScript Answers

How to stop event propagation with inline onclick attribute with JavaScript?

To stop event propagation with inline onclick attribute with JavaScript, we can call the stopPropagation method.

For instance, we write

<div onclick="onClick(event);">click me</div>

to set the onclick attribute to call the onClick function with the click event object.

Then we write

function onClick(event) {
  event.stopPropagation();
}

to define the onClick function to call the stopPropagation method to stop the click event from bubbling up.

Categories
JavaScript Answers

How to use HTML5/JavaScript to generate and save a file?

To use HTML5/JavaScript to generate and save a file, we create a link.

For instance, we write

const link = document.createElement("a");
link.setAttribute(
  "href",
  "data:text/plain;charset=utf-8," + encodeURIComponent(text)
);
link.setAttribute("download", filename);
link.click();

to call createElement to create a link.

Then we call setAttribute to set the href attribute to the base64 URL of the file we want to download.

We call setAttribute again to set the download attribute to the name of the downloaded file.

Finally, we call click to download the file.

Categories
JavaScript Answers

How to make an HTML back link with JavaScript?

To make an HTML back link with JavaScript, we call the history.back method on click.

For instance, we write

<a href="javascript:history.back()">Go Back</a>

to set the href attribute to the JavaScript code that calls the history.back method to go back to the previous page when we click on the link.

Categories
JavaScript Answers

How to check whether a Storage item is set with JavaScript?

To check whether a Storage item is set with JavaScript, we use the getItem method.

For instance, we write

if (localStorage.getItem("infiniteScrollEnabled") === null) {
  //...
}

to check if the local storage item with key 'infiniteScrollEnabled' with the getItem method.

If it’s null, then the item with key 'infiniteScrollEnabled' doesn’t exist in local storage.

Categories
JavaScript Answers

How to load up CSS files using JavaScript?

To load up CSS files using JavaScript, we create an element with createElement.

For instance, we write

const link = document.createElement("link");
link.href = src;
link.rel = "stylesheet";
document.head.append(link);

to call createElement to create a link element.

And then we set its href and rel attributes by setting the properties with the same name.

Then we call document.head.append to append the link element as the last child of the head element.