Categories
JavaScript Answers

How to set HTML5 required attribute in JavaScript?

To set HTML5 required attribute in JavaScript, we set the required property.

For instance, we write

document.getElementById("edName").required = true;

to select the input with getElementById.

And then we set its required property to true to make it a required input.

Categories
JavaScript Answers

How to target an elements parent element using event.target with JavaScript?

To target an elements parent element using event.target with JavaScript, we use the parentNode property.

For instance, we write

const handleEvent = (e) => {
  const parent = e.currentTarget.parentNode;
};

to define the handleEvent function.

It it, we get the current element that triggered the event with e.currentTarget.

And we get its parent node with the parentNode property.

Categories
JavaScript Answers

How to make a non-cached request with fetch and JavaScript?

To make a non-cached request with fetch and JavaScript, we set the cache option.

For instance, we write

const res = await fetch("some.json", { cache: "no-store" });

to call fetch to make a request to get some.json with a get request.

We set cache to 'no-store' to bypass the cache and get the latest version of some.json.

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.