Categories
JavaScript Answers

How to fix “Uncaught TypeError: Illegal invocation” in Chrome and JavaScript?

To fix "Uncaught TypeError: Illegal invocation" in Chrome and JavaScript, we should make sure we’re calling a function.

For instance, we write

const obj = {
  someProperty: true,
  someMethod() {
    console.log(this.someProperty);
  },
};
obj.someMethod();

to define the obj with the someMethod method.

Then we call it with obj.someMethod();.

It logs true since this is the obj object.

Categories
JavaScript Answers

How to include both href and onclick in an HTML a tag with JavaScript?

To include both href and onclick in an HTML a tag with JavaScript, we add both attributes.

For instance, we add a link with

<a href="www.example.com" onclick="return onClick();">Item</a>

We define the onClick function with

function onClick() {
  // ...
}

We set onclick to return the return value of onClick so that if onClick returns false, the link won’t navigate to the href URL.

onClick is called when the link is clicked.

Categories
JavaScript Answers

How to host Material icons offline with JavaScript?

To host Material icons offline with JavaScript, we can install the material-icons-font package.

We install it by running

npm install material-icons-font --save

Then we add some @import statements into our SCSS code by writing

@import "~material-icons-font/sass/variables";
@import "~material-icons-font/sass/mixins";
$MaterialIcons_FontPath: "~material-icons-font/fonts";
@import "~material-icons-font/sass/main";
@import "~material-icons-font/sass/Regular";

to include the icon files.

Then we use it by writing

<i class="material-icons">face</i>
<i class="material-icons md-48">face</i>
<i class="material-icons md-light md-inactive">face</i>
Categories
JavaScript Answers

How to stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

To stop a web page from scrolling to the top when a link is clicked that triggers JavaScript, we call the preventDefault method.

For instance, we write

document.getElementById("#ma_link").addEventListener("click", (e) => {
  e.preventDefault();
  doSomething();
});

to select the link with getElementById.

Then we call addEventListener to add a click listener to it.

And we call e.preventDefault in the click listener to stop the scrolling.

Categories
JavaScript Answers

How to access form elements by HTML ID or name attribute with JavaScript?

To access form elements by HTML ID or name attribute with JavaScript, we use the elements property.

For instance, we write

<form id="myForm">
  <input type="text" name="foo" />
</form>

to add a form.

Then we write

const fooInput = document.getElementById("myForm").elements["foo"];

to get the input inside the form.

We select the form with getElementById.

And then we get the input with the elements["foo"] property.

'foo' is the name attribute value of the input.