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
Vue Answers

How to get selected option on @change with Vue.js?

To get selected option on @change with Vue.js, we should use v-model to bind the selected value to a reactive property.

For instance, we write

<select
  name="LeaveType"
  @change="onChange($event)"
  class="form-control"
  v-model="key"
>
  <option value="1">Annual Leave/ Off-Day</option>
  <option value="2">On Demand Leave</option>
</select>
<script>
  const vm = new Vue({
      data: {
          key: ""
      },
      methods: {
          onChange(event) {
              console.log(event.target.value)
          }
      }
  }
</script>

to add a select drop down.

We bind the key reactive property to the value of the selected value of the drop down with v-model.

Also we can get the value from event.target.value from the change event handler.

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.