Categories
JavaScript Answers

How to Determine if an HTML Element’s Content Overflows with JavaScript?

The HTML element’s scrollWidth property has the full width of the content in an element.

The HTML element’s scrollHeight property has the full height of the content in an element.

The HTML element’s clientWidth property has the width of the content in an element that’s displayed.

The HTML element’s clientHeight property has the height of the content in an element that’s displayed.

Therefore, we can compare them to see if any content overflows.

If scrollWidth is bigger than clientWidth or scrollHeight is bigger than clientHeight , then we know content is overflowing.

For instance, if we have the following HTML:

<div style='width: 100px; height: 100px; overflow: auto'>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer efficitur mauris at nisl accumsan suscipit. Aliquam tempus ultrices consectetur.
</div>

Then we can check if the div’s content is overflowing the div by writing:

const checkOverflow = (el) => {
  const isOverflowing = el.clientWidth < el.scrollWidth ||
    el.clientHeight < el.scrollHeight;
  return isOverflowing;
}

const div = document.querySelector('div')
console.log(checkOverflow(div))

We create the checkOverflow function that takes the el DOM element object as the parameter.

And return the comparison between clientWidth and scrollWidth and clientHeight and scrollHeight as we described.

The console log should log true since the text in the div overflows the height of the div, so el.clientHeight < el.scrollHeight returns true .

Categories
JavaScript Answers

How to Get the Number of Digits of a Number with JavaScript?

We can get the number of digits of a non-negative integer with the Number.prototype.toString method.

For instance, we can write:

const getLength = (number) => {  
  return number.toString().length;  
}  
console.log(getLength(12345))

to get the number of digits of 12345.

To do that, we create the getLength function that takes the number parameter.

And we return the length of the string form of number .

Therefore, the console log should log 5 since 12345 has 5 digits.

Get the Number of Digits of Decimal Numbers

We can’t use toString to get the number of digits of decimal numbers since it just returns the string form of the number, including all the decimal digits and other characters that comes with the number.

To get the number of digits of a decimal number, we can use math methods.

For instance, we can write:

const getLength = (number) => {  
  return Math.max(Math.floor(Math.log10(Math.abs(number))), 0) + 1;  
}  
console.log(getLength(12345.67))

to get the number of digits of number by taking the log with 10 of it and then add 1 to get the number of digits of it.

We have to make sure number is converted to a positive number with Math.abs so we can take the log of it.

Next, we call Math.floor to take the floor of the log to get the number of digits excluding the leftmost digit.

Then we get the floor of the log and 0 with Math.max and add 1 to get the number of digits.

Therefore, the console log should log 5 since we use the log operation to discard the decimal digits.

Categories
JavaScript Answers

How to Get HTML Form Values with JavaScript?

We can use the FormData constructor to create an object that gets the key-value pairs of the form values we entered.

For instance, if we have the following form:

<form>
  Credit Card Validation:
  <input type="text" name="cctextbox">
  <br />

  Card Type:
  <select name="cardtype">
    <option value="visa">Visa</option>
    <option value="mastercard">MasterCard</option>
    <option value="discover">Discover</option>
    <option value="amex">Amex</option>
    <option value="diners">Diners Club</option>
  </select>
  <br />
  <input type="submit" />
</form>

Then we can write:

const form = document.querySelector('form')
form.addEventListener('submit', (e) => {
  e.preventDefault()
  const formData = new FormData(form)
  for (const pair of formData.entries()) {
    console.log(pair)
  }
})

to listen to the submit event of the form and get the value when we submit.

We first get the form element with document.querySelector .

Then we call addEventListener to add the submit event listener to the form.

The 2nd argument of addEventListener is the submit event listener.

We call e.preventDefault to prevent the default submit behavior so we can do client-side form submission.

Then we create the formData object with the FormData constructor with the form as the argument to get the form data values.

And then we call formData.entries to get an array of form data key-pair pairs.

Then pair should be something like:

["cctextbox", "aa"]
["cardtype", "visa"]

where the first entry if the name attribute value and the 2nd entry is the entered value.

Categories
JavaScript Answers

How to Text Area to Resize Based on Content Length with JavaScript?

The scrollHeight property of the text area element has the full height of the content in pixels.

Therefore, we just need to set the height of the text area to the scroll height to set the height of the text area to wrap around all the content of the text area.

For instance, if we have the following HTML:

<textarea></textarea>

Then we can get the text area and then set the height to the scroll height by writing:

const textarea = document.querySelector('textarea')
textarea.addEventListener('keyup', () => {
  textarea.style.height = `${textarea.scrollHeight}px`;
})

We get the text area with document.querySelector .

Then we call addEventListener with 'keyup' as the first argument to add a keyup listener for the text area.

In the event listener, we set the style.height to textarea.scrollHeight to set the height of the text area to the height of the content inside.

We should remember to include the unit so that the height will be set.

Now when we type into the text area, it’ll resize the height to wrap around all the content.

Categories
JavaScript Answers

How to Check if Image Exists on the Server Using JavaScript?

Sometimes, we want to check if an image exists on the server with JavaScript.

In this article, we’ll look at how to check if an image exists on the server with JavaScript.

Listen to the Image error Event

We can listen to the error event trigger by the image element when the image fails to load to check whether there’s any errors trigger from loading the image from the server.

For instance, we can write:

const image = new Image();

image.onload = () => {
  document.body.appendChild(image);
}
image.onerror = () => {
  const err = new Image();
  err.src = 'https://i.picsum.photos/id/918/200/300.jpg?hmac=1gEvFp6O-XDh4848VnlwyOIrVy8s_aJNhYyTzxN9_JA';
  document.body.appendChild(err);
}

image.src = "abc";

We use the Image constructor to create an image DOM element object.

Then we set the img.onload property to a function that runs when the image loads successfully.

In the function, we call document.body.appendChild to add the image to the body element.

Next, we set the img.onerror property to a function that runs when the original image fails to load.

In the function, we create a new Image instance and set the src to an image that we load in case the original one fails to load.

Finally, we set image.src to an invalid URL so the onerror method runs and loads the fallback image.

Conclusion

We can listen to the error event of an image to see when the original image we’re loading fails to load.