Categories
JavaScript Answers

How to Scroll to the Bottom of a Div with JavaScript?

Sometimes, we want to add a feature to let users scroll to the bottom of a div.

In this article, we’ll look at how to scroll to the bottom of a div with JavaScript.

Set scrollTop to scrollHeight

One way to scroll to the bottom of a div with JavaScript is to set the scrollTop property of the div object to the scrollHeight property of the same object.

For instance, we can write the following HTML:

<button>
  scroll to bottom
</button>
<div style='height: 300px; overflow-y: scroll'>
</div>

Then we can write the following JavaScript code:

const div = document.querySelector('div')
const button = document.querySelector('button')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}
button.addEventListener('click', () => {
  div.scrollTop = div.scrollHeight;
})

We set the height of the div to 300px and overflow-y to scroll to make the div scrollable.

Then in the JavaScript code, we get the div and the button.

Before we add the scrolling code, we add a for loop to create a p element and call appendChild to append the p elements to the div.

Next, we call addEventListener to add a click event listener to the button.

Then we set scrollTop to scrollHeight as we did in the callback to scroll to the bottom of the div.

scrollHeight is the height of an element’s content, including content that’s not visible on the screen due to overflow.

Set scrollTop to scrollHeight — clientHeight

clientHeight is CSS height + CSS padding + height of the horizontal scrollbar if prssent.

We can subtract that from scrollHeight and scroll to the bottom.

So we can write:

const div = document.querySelector('div')
const button = document.querySelector('button')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}
button.addEventListener('click', () => {
  div.scrollTop = div.scrollHeight - div.clientHeight;
})

and keep the HTML the same.

We still scroll down to the content height by setting scrollTop to the height of the content.

We just omit the scrollbar height.

The scrollIntoView Method

Another way to scroll to the bottom of a div is to select the element at the bottom of the div.

Then we can call scrollIntoView on it to scroll to the bottom.

For instance, we can write:

const div = document.querySelector('div')
const button = document.querySelector('button')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  p.id = `el-${i}`
  div.appendChild(p)
}
button.addEventListener('click', () => {
  const bottomEl = document.querySelector('#el-100')
  bottomEl.scrollIntoView({
    behavior: 'smooth',
    block: 'end'
  });
})

to call scrollIntoView on the bottomEl , which is the element with ID el-100 .

This element is at the bottom of the div, so we’ll scroll to the bottom.

behavior set the scroll behavior.

'smooth' lets us do smooth scrolling.

block is set to 'end' to scroll to the end of the element.

Conclusion

There’re several ways we can use to scroll to the bottom of a div with JavaScript.

Categories
JavaScript Answers

How to Scroll to the Bottom of a Div with JavaScript?

Sometimes, we want to add a feature to let users scroll to the bottom of a div.

In this article, we’ll look at how to scroll to the bottom of a div with JavaScript.

Set scrollTop to scrollHeight

One way to scroll to the bottom of a div with JavaScript is to set the scrollTop property of the div object to the scrollHeight property of the same object.

For instance, we can write the following HTML:

<button>
  scroll to bottom
</button>
<div style='height: 300px; overflow-y: scroll'>
</div>

Then we can write the following JavaScript code:

const div = document.querySelector('div')
const button = document.querySelector('button')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}
button.addEventListener('click', () => {
  div.scrollTop = div.scrollHeight;
})

We set the height of the div to 300px and overflow-y to scroll to make the div scrollable.

Then in the JavaScript code, we get the div and the button.

Before we add the scrolling code, we add a for loop to create a p element and call appendChild to append the p elements to the div.

Next, we call addEventListener to add a click event listener to the button.

Then we set scrollTop to scrollHeight as we did in the callback to scroll to the bottom of the div.

scrollHeight is the height of an element’s content, including content that’s not visible on the screen due to overflow.

Set scrollTop to scrollHeight — clientHeight

clientHeight is CSS height + CSS padding + height of the horizontal scrollbar if prssent.

We can subtract that from scrollHeight and scroll to the bottom.

So we can write:

const div = document.querySelector('div')
const button = document.querySelector('button')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}
button.addEventListener('click', () => {
  div.scrollTop = div.scrollHeight - div.clientHeight;
})

and keep the HTML the same.

We still scroll down to the content height by setting scrollTop to the height of the content.

We just omit the scrollbar height.

The scrollIntoView Method

Another way to scroll to the bottom of a div is to select the element at the bottom of the div.

Then we can call scrollIntoView on it to scroll to the bottom.

For instance, we can write:

const div = document.querySelector('div')
const button = document.querySelector('button')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  p.id = `el-${i}`
  div.appendChild(p)
}
button.addEventListener('click', () => {
  const bottomEl = document.querySelector('#el-100')
  bottomEl.scrollIntoView({
    behavior: 'smooth',
    block: 'end'
  });
})

to call scrollIntoView on the bottomEl , which is the element with ID el-100 .

This element is at the bottom of the div, so we’ll scroll to the bottom.

behavior set the scroll behavior.

'smooth' lets us do smooth scrolling.

block is set to 'end' to scroll to the end of the element.

Conclusion

There’re several ways we can use to scroll to the bottom of a div with JavaScript.

Categories
JavaScript Answers

How to Restrict HTML Text Input to Only Allow Numbers?

Sometimes, we only want users to enter numbers into an HTML text input.

In this article, we’ll look at how to restrict HTML text input to only allow numbers.

Watching Keypresses

We can watch keypresses by checking for inputted values and pasted data.

To do this, we write the following HTML:

<input type="text" />

And we can write the following JavaScript:

const input = document.querySelector("input");
input.addEventListener("keypress", (evt) => {
  const theEvent = evt || window.event;
  let key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode(key);
  const regex = /[0-9]|./;
  if (!regex.test(key)) {
    theEvent.returnValue = false;
    if (theEvent.preventDefault) theEvent.preventDefault();
  }
});

We listen to the keypress event with an event listener.

In the keypress event callback, we get the keyCode property to get the code.

Then we get the value of key pressed with String.fromCharCode .

Then we call regex.test to check if the key value is a digit.

If it’s not, then we call preventDefault() to prevent the character from being added to the inputted value string.

Also, we can just remove all the non-digit characters from the inputted value string.

For instance, we can write:

const input = document.querySelector("input");
input.addEventListener("keyup", (evt) => {
  input.value = evt.target.value.replace(/[^d]/, "");
});

We get the inputted value with evt.target.value ,.

And we call replace to get all the non-digit characters with an empty string.

Then we assign the returned string to input.value to update the inputted value.

Set Input Type Attribute to number

Also, we can just set the type attribute of input to number .

To do this, we write:

<input type='number' />

Then we don’t need to add any JavaScript code to remove the non-digit characters from the inputted value string.

Conclusion

There’re several ways to restrict an input’s value to digits only.

Categories
JavaScript Answers

How to Add Colors in JavaScript Console Log Output?

To make console long output easier to see, we can add colors to JavaScript’s console log.

In this article, we’ll look at how to add colors to console log output in the browser dev console.

Add CSS Styles to Console Log Output

We can add CSS styles to console log output with the %c tag.

For instance, we can write:

console.log('%c hello world ', 'background: #222; color: #bada55');

We add the %c tag so that we can apply the CSS styles in the 2nd argument to the hello world text.

We set the background property to set the background color.

And we set the color property to change the text color.

The console.error Method

The console.error method lets us log things with a red background.

This lets us show data in more obvious ways.

For instance, we can write:

console.error("hello world");

to use the method.

The console.warn Method

The console.warn method lets us log things on a yellow background.

To use it, we write:

console.warn("hello world");

Bash Color Flags

Also, console.log lets us add Bash color flags to set the color of the text.

For instance, we can write:

console.log('x1B[31mhellox1B[34m world');

x1B[31 means red.

And x1B[34m is blue.

Also, we can set the background color of text by writing:

console.log('x1b[43mhighlighted');

x1b[43m sets the background color to yellow.

Conclusion

We can log colored text to the browser development console with various tricks.

Some console methods lets us change colors in various ways.

Categories
JavaScript Answers

How to Sort an Array of Integers Correctly with JavaScript?

Sorting an array of integers is something that we’ve to a lot in our JavaScript app.

In this article, we’ll look at how to sort an array of integers correctly in our JavaScript app.

Array.prototype.sort

The sort method lets us sort an array by passing in a comparator function.

To use it to sort numbers, we write:

const arr = [4, 2, 1, 3]
const sorted = arr.sort((a, b) => a - b);
console.log(sorted)

to do an ascending sort.

So sorted is [1, 2, 3, 4] .

The numbers will be swapper if the callback’s return value is positive, so we get them sorted in ascending order.

To sort in descending order, we just swap a and b in the expression we return:

const arr = [4, 2, 1, 3]
const sorted = arr.sort((a, b) => b - a);
console.log(sorted)

We must use sort with the callback so that we can compare the numbers.

Then sorted is [4, 3, 2, 1] .

If we don’t pass in a callback, then sort assumes that we’re sorting strings.

And it’ll try to sort items alphabetically.

We can just use Math.sign to return -1 for if an argument is a negative number, 0 if the argument is 0, and 1 if the number is positive.

So we can write:

const arr = [4, 2, 1, 3]
const sorted = arr.sort((a, b) => Math.sign(a - b));
console.log(sorted)

to sort ascending.

And:

const arr = [4, 2, 1, 3]
const sorted = arr.sort((a, b) => Math.sign(b - a));
console.log(sorted)

to sort descending.

Conclusion

To sort an JavaScript array with numbers correctly, we should pass in a comparator function to compare the numbers if we use sort .

Otherwise, it’ll assume that we’re sorting strings and will try to sort the items alphabetically.