Categories
JavaScript Answers

How to Count the Number of Lines of Text Inside a DOM Element with JavaScript?

To get the number of lines in an element, we can divide the element’s height by its line-height.

For instance, if we have the following HTML:

<div style="line-height: 20px">  
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tristique nec magna non faucibus. Cras ut mi dignissim, tristique elit at, porta lorem. Pellentesque et odio sed enim commodo commodo in sit amet nunc. Phasellus eu tempus felis, id aliquet leo. Curabitur mollis mauris non dui ornare,  
</div>

Then we can do the computation by writing:

const el = document.querySelector('div');  
const divHeight = +el.offsetHeight  
const lineHeight = +el.style.lineHeight.replace('px', '');  
const lines = divHeight / lineHeight;  
console.log(lines);

We have to set the line height explicitly with the CSS line-height property as we did in the HTML.

Then we select the div with document.querySelector .

Next, we get the div’s height by using the offsetHeight property.

Then we get the lineHeight with the el.style.lineHeight property, we remove the 'px' so that we can convert the string to a number with + .

Next, we divide divHeight by lineHeight to get the number of lines in the div.

Categories
JavaScript Answers

How to Use await on an Rx js Observable?

To use await with Rxjs observables, we’ve to convert it to a promise first.

To do that, we can use the firstValueFrom or lastValueFrom functions.

firstValueFrom returns promise that resolves to the first value of an observable.

lastValueFromreturns promise that resolves to the last value of an observable.

For instance, we can use it by writing:

import { firstValueFrom, lastValueFrom, of } from "rxjs";

(async () => {
  const myObservable = of(1, 2, 3);
  const first = await firstValueFrom(myObservable);
  console.log(first);
  const last = await lastValueFrom(myObservable);
  console.log(last);
})();

We have the myObservable observable, which we created by calling the of function.

of returns an observable that emits the arguments that we pass in sequentially.

Then we call firstValueFrom with myObservable .

Then we see that first is 1.

Next, we call lastValueFrom with myObservable .

The last is 3.

Categories
JavaScript Answers

How to Add target=“_blank” to window.location in JavaScript?

Use window.open

The window.open method lets us open a new window or tab from a given tab.

For instance, we can write:

window.open('http://example.com', '_blank');

to open a new tab that opens http://example.com.

_blank means we open a new window.

Categories
JavaScript Answers

How to Fix the ‘Cannot read property style of undefined’ Error with jQuery DataTables?

Sometimes, we get the ‘Cannot read property style of undefined’ when we try to add a table with jQuery DataTables.

In this article, we’ll look at ‘Cannot read property style of undefined’ when we try to add a table with jQuery DataTables.

th Element Mismatch

One cause of this error is that the number of th elements in the table header or footer doesn’t match the columns defined in the columns option.

Therefore, we should make sure that both of them match.

colspan Mismatch

If we have colspan in the table header, we should make sure that at least 2 header rows and one unique th element for each column.

Use Zero-Based Colum Index to Refer to Existing Columsn with adding the columnDefs.targets Property

If we add the columnDefs.targets property, we should make sure that the array has indexes that aren’t out of bounds when counting from 0.

For instance, if we have the following HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>
<script src='//cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js'></script>
<link rel='stylesheet' href='//cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css'>
<table>

</table>

Then we can write the following JavaScript code:

const dataSet = [
  ["Tiger Nixon", "System Architect", "Edinburgh", "5421", "2011/04/25", "$320,800"],
  ["Garrett Winters", "Accountant", "Tokyo", "8422", "2011/07/25", "$170,750"],
  ["Ashton Cox", "Junior Technical Author", "San Francisco", "1562", "2009/01/12", "$86,000"],
  ["Cedric Kelly", "Senior Javascript Developer", "Edinburgh", "6224", "2012/03/29", "$433,060"],
  ["Airi Satou", "Accountant", "Tokyo", "5407", "2008/11/28", "$162,700"],
  ["Brielle Williamson", "Integration Specialist", "New York", "4804", "2012/12/02", "$372,000"],
  ["Herrod Chandler", "Sales Assistant", "San Francisco", "9608", "2012/08/06", "$137,500"],
  ["Rhona Davidson", "Integration Specialist", "Tokyo", "6200", "2010/10/14", "$327,900"],
  ["Colleen Hurst", "Javascript Developer", "San Francisco", "2360", "2009/09/15", "$205,500"],
  ["Sonya Frost", "Software Engineer", "Edinburgh", "1667", "2008/12/13", "$103,600"],
  ["Jena Gaines", "Office Manager", "London", "3814", "2008/12/19", "$90,560"],
  ["Quinn Flynn", "Support Lead", "Edinburgh", "9497", "2013/03/03", "$342,000"],
  ["Charde Marshall", "Regional Director", "San Francisco", "6741", "2008/10/16", "$470,600"],
  ["Haley Kennedy", "Senior Marketing Designer", "London", "3597", "2012/12/18", "$313,500"],
  ["Tatyana Fitzpatrick", "Regional Director", "London", "1965", "2010/03/17", "$385,750"],
  ["Michael Silva", "Marketing Designer", "London", "1581", "2012/11/27", "$198,500"],
]

jQuery('table').DataTable({
  data: dataSet,
  columns: [{
      title: "Name"
    },
    {
      title: "Position"
    },
    {
      title: "Office"
    },
    {
      title: "Extn."
    },
    {
      title: "Start date"
    },
    {
      title: "Salary"
    }
  ],
  columnDefs: [{
    orderable: false,
    targets: [0, 1, 2]
  }]
});

to add the columnDefs.targets property.

0 is the first column, 1 is the 2nd one, and 2 is the 3rd one.

We set orderable to false so we disabled reordering items for those columns.

Conclusion

To fix the ‘Cannot read property style of undefined’ when we try to add a table with jQuery DataTables, we should make sure the th elements and colspan matches the number of columns.

Also, we should make sure the columnDefs.targets property should match the indexes of the columns in the table.

Categories
JavaScript Answers

How to Validate Floats and Decimal Separators with the HTML5 Number Input?

Sometimes, we want to validate floating-point numbers with decimal separators with the HTML5 number input.

In this article, we’ll look at how to validate floats and decimal separators with HTML5 number input.

Add the pattern Attribute

We can add the pattern attribute to an HTML5 number input to add validation to the input.

For instance, we can write:

<input type="number" name="price" pattern="[0-9]+([.,][0-9]+)?" step="0.01" >

Then we can write the following JavaScript code to get the value when we’re done typing on the input and move focus away from the input:

const input = document.querySelector('input')
input.addEventListener('change', (e) => {
  console.log(e.target.value)
})

The pattern attribute will restrict the value that’s entered along with the number input type.

And in the JavaScript code, we call addEventListener to listen to the change event which is triggered when we stop typing and move focus away from the input.

We get the value entered into the input with e.target.input .

Conclusion

We can add the pattern attribute to an HTML5 number input to add validation to the input.