Categories
JavaScript Answers

How to get the raw value a number input field with JavaScript?

To get the raw value a number input field with JavaScript, we select the input value and return it.

For instance, we write

input.focus();
document.execCommand("SelectAll");
const displayValue = window.getSelection().toString();

to focus on the input with focus.

Then we call execCommand to select everything in the input box.

Finally, we get the selected text with getSelection and convert it to a string with toString.

Categories
JavaScript Answers

How to simulate a hover with a touch in touch enabled browsers with CSS and JavaScript?

To simulate a hover with a touch in touch enabled browsers with CSS and JavaScript, we listen to the touchstart event.

For instance, we write

document.addEventListener("touchstart", () => {}, true);

to add a touchstart event listener to document.

Then we write

element:hover,
element:active {
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  -webkit-user-select: none;
  -webkit-touch-callout: none;
}

to set the touch highlight color with -webkit-tap-highlight-color: rgba(0, 0, 0, 0);.

We disable context menu on long press with -webkit-touch-callout: none.

Categories
JavaScript Answers

How to add “href” attribute to a link dynamically using JavaScript?

To add "href" attribute to a link dynamically using JavaScript, we call the setAttribute method.

For instance, we write

const a = document.getElementById("link");
a.setAttribute("href", url);

to select the link with getElementById.

Then we call setAttribute to set the href attribute value to url.

Categories
JavaScript Answers

How to paste as plain text with JavaScript execCommand?

To paste as plain text with JavaScript execCommand, we get the pasted data as plain text before we insert it.

For instance, we write

editor.addEventListener("paste", (e) => {
  e.preventDefault();
  const text = e.clipboardData.getData("text/plain");
  document.execCommand("insertHTML", false, text);
});

to listen to the past event on editor with addEventListener.

In it, we call preventDefault to stop the default paste behavior.

Then we get the pasted text as plain text by calling clipboardData.getData with 'text/plain',

Finally, we call execCommand to insert the text into editor.

Categories
JavaScript Answers

How to play a notification sound on websites with JavaScript?

To play a notification sound on websites with JavaScript, we call the play method.

For instance, we write

const audio = new Audio(url);
audio.play();

to create an audio element with the audio url with the Audio constructor.

Then we call play to play the clip.