Categories
JavaScript Answers

How to force page scroll position to top at page refresh in HTML with JavaScript?

To force page scroll position to top at page refresh in HTML with JavaScript, we add a beforeunload event handler.

For instance, we write

window.onbeforeunload = () => {
  window.scrollTo(0, 0);
};

to set window.onbeforeunload to a function that calls window.scrollTo with 0 and 0.

Then right before the page is refreshed, the function is called to scroll the page to the top.

Categories
JavaScript Answers

How to put a clear button inside my HTML text input box like the iPhone does?

To put a clear button inside my HTML text input box like the iPhone does, we add a search input.

For instance, we write

<input type="search" placeholder="Search..." />

to add a search input by adding an input element with the type attribute set to search.

Categories
JavaScript Answers

How to remove padding or margins from Google Charts with JavaScript?

To remove padding or margins from Google Charts with JavaScript, we set the width and height of the chart area.

For instance, we write

const options = {
  title: "How Much Pizza I Ate",
  width: 350,
  height: 400,
  chartArea: { width: "100%", height: "80%" },
  legend: { position: "bottom" },
};

to set the chartArea‘s width and height to match the actual width and height to remove any padding or margin from the chart.

Categories
JavaScript Answers

How to add upload progress indicators for fetch with JavaScript?

To add upload progress indicators for fetch with JavaScript, we use axios.

For instance, we write

const { data } = await axios.request({
  method: "post",
  url: "/example",
  data: myData,
  onUploadProgress: (p) => {
    console.log(p);
  },
});

to call axios.request to make a post request by calling it with an object with method set to 'post'.

We make a request to the '/example' URL.

We set onUploadProgress to a function that logs progress p.

Categories
JavaScript Answers

How to get element by name with JavaScript?

To get element by name with JavaScript, we use the getElementsByName method.

For instance, we write

const val = document.getElementsByName("acc")[0].value;

to select the first element with name attribute acc with

document.getElementsByName("acc")[0]

Then we get its value with the value property.