Categories
JavaScript Answers

How to count text lines inside an DOM element with JavaScript?

To count text lines inside an DOM element with JavaScript, we can calculate it from the element height and its line height.

For instance, we write

const el = document.getElementById("content");
const divHeight = el.offsetHeight;
const lineHeight = parseInt(el.style.lineHeight);
const lines = divHeight / lineHeight;
console.log(lines);

to get the element with getElementById.

We get its height with offsetHeight.

We get its line height with el.style.lineHeight.

Then we divide divHeight by lineHeight to get the number of lines.

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.