Categories
JavaScript Answers

How to unescape HTML entities in JavaScript?

To unescape HTML entities in JavaScript, we can use the DOMParser constructor.

For instance, we write

const htmlDecode = (input) => {
  const doc = new DOMParser().parseFromString(input, "text/html");
  return doc.documentElement.textContent;
};

console.log(htmlDecode("<img src='myimage.jpg'>"));

to define the htmlDecode function.

In it, we get the input string and parse it into a DOM object.

We create a DOMParser object and call it parseFromString method with the input and MIME type string to parse the input into a DOM object.

Then we get the textContent from the DOM object to get the HTML string unescaped.

Categories
JavaScript Answers

How to stop form submission with JavaScript?

To stop form submission with JavaScript, we call the preventDefault method.

For instance, we write

<form onsubmit="submitForm(event)">
  <input type="text" />
  <input type="submit" />
</form>

to add a form.

We set its onsubmit attribute to call the submitForm function with the submit event object.

Then we write

function submitForm(event) {
  event.preventDefault();
}

to define the submitForm function.

In it, we call event.preventDefault to stop form submissmision when we click on the submit button in the form.

Categories
JavaScript Answers

How to fix “uncaught typeerror: cannot read properties of null (reading ‘addEventListener’)” error with JavaScript?

To fix "uncaught typeerror: cannot read properties of null (reading ‘addEventListener’)" error with JavaScript, we should make sure the element we’re calling addEventListener on isn’t null.

For instance, we write

const el = document.getElementById("overlayBtn");
if (el) {
  el.addEventListener("click", onClick, false);
}

to call getElementById to get the element we want to add the click listener to.

Then if el isn’t null, then we call addEventListener on it to add the onClick function as its click event listener.

Categories
JavaScript Answers

How to simulate keypress with JavaScript?

To simulate keypress with JavaScript, we can call the dispatchEvent method to trigger an event of our choice.

For instance, we can write:

window.addEventListener('keydown', (e) => {
  console.log(e)
})

window.dispatchEvent(new KeyboardEvent('keydown', {
  'key': 'a'
}));

to listen to the keydown event and trigger it.

We call addEventListener with 'keydown' to listen to the keydown event.

Then to trigger the keydown event, we call window.dispatchEvent with a KeyboardEvent instance.

We pass in the type of keyboard event to trigger into the first argument of the constructor.

And we pass in an object with the options to set in the event object into the 2nd argument.

Therefore, after dispatchEvent is run, then e.key should be 'a' when logged in the callback.

We can set more options in the object.

For instance, we can write:

window.addEventListener('keydown', (e) => {
  console.log(e)
})

window.dispatchEvent(new KeyboardEvent('keydown', {
  key: "e",
  keyCode: 69,
  code: "KeyE",
  which: 69,
  shiftKey: false,
  ctrlKey: false,
  metaKey: false
}));

to set more options in the object.

keyCode is the numeric code of the key that we want to set.

code has the name of the key.

which has the keyboard key number.

shiftKey sets whether we want to press the shift key in addition to the key we’re pressing.

ctrlKey sets whether we want to press the Ctrl key in addition to the key we’re pressing.

metaKey sets whether we want to press the meta key in addition to the key we’re pressing.

The meta key is the Windows key on PC keyboards and the command key on Mac keyboards.

When the event is triggered, we should see all the options logged in the addEventListener callback.

They should be in the same properties in the e object as in the options object we pass into the KeyboardEvent constructor.

We can write the same code with the keyup event.

We just replace 'keydown' with 'keyup' everywhere.

Categories
JavaScript Answers

How to fix Jest ‘encountered an unexpected token import’ error with JavaScript?

To fix Jest ‘encountered an unexpected token import’ error with JavaScript, we set the Jest config to allow modules.

For instance, in jest.config.js, we write

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  roots: ["./src"],
  transform: { "\\.ts$": ["ts-jest"] },
  testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
  globals: {
    "ts-jest": {
      tsConfig: {
        allowJs: true,
      },
    },
  },
};

to allow extensions for modules by setting moduleFileExtensions to ["ts", "tsx", "js", "jsx", "json", "node"].

We set allowJs to true to allow JavaScript code to run including modules.

And we set transform to { "\\.ts$": ["ts-jest"] } to transform them with ts-jest so they can be run with Jest.