Categories
JavaScript Answers

How to Use the toLocaleTimeString Method to Return a Formatted Date and Time String Without Including the Seconds?

Sometimes, we want to format a JavaScript date object into a time string but omit the seconds from the string.

In this article, we’ll look at ways to use the toLocaleTimeString method to return a formatted time string without including the seconds in the string.

Set hour and minute to 2-digit

We can set the hour and minute properties to '2-digit' to get rid of the seconds from the returned time string.

For instance, we can write:

const dateWithoutSecond = new Date();
const formatted = dateWithoutSecond.toLocaleTimeString([], {
  hour: '2-digit',
  minute: '2-digit'
});
console.log(formatted)

We create a Date instance and store it in the dateWithoutSecond variable.

Then we call toLocateString on it with an object with the hour and minute options set to '2-digit' to return a time string without the seconds.

So formatted would be a string like '04:05 PM’ .

Set timeStyle to short

We can also set the timeStyle option to short to omit the seconds from the returned time string.

For instance, we can write:

const dateWithoutSecond = new Date();
const formatted = dateWithoutSecond.toLocaleTimeString([], {
  timeStyle: 'short'
});
console.log(formatted)

to do this.

Then formatted is something like '4:07 PM’ .

Conclusion

We can set various options with toLocateTimeString to return a time string without the seconds part.

Categories
JavaScript Answers

How to Check for text-overflow Ellipsis in an HTML Element?

Sometimes, we want to check whether the text-overflow ellipsis is rendered in the element.

In this article, we’ll look at how to check for the text-overflow ellipsis in an HTML element.

Check if offsetWidth is Less than scrollWidth

The offsetWidth property of an element tells us the width of the element rendered on the screen.

scrollWidth tells us the width of the element including the truncated parts.

Therefore, we can see if a piece of text is truncated with the CSS text-overflow property by checking whether offsetWidth is less than scrollWidth .

For instance, if we have the following HTML:

<div>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam in neque laoreet, venenatis quam id, tristique ipsum. Sed augue ipsum, pharetra in ipsum eget, varius placerat odio. Pellentesque a luctus metus, commodo placerat elit. Nullam efficitur augue in magna consectetur finibus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras porttitor lectus pretium, placerat nulla eget, hendrerit magna. Nunc in sem dui. Sed sollicitudin sem a massa malesuada cursus. Mauris feugiat enim sit amet efficitur lobortis.
</div>

And CSS:

div {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Then we can do the check by writing:

const isEllipsisActive = (e) => {
  return (e.offsetWidth < e.scrollWidth);
}

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

We do the comparison between offsetWidth and scrollWidth as we specified in the isEllipsisActive function.

Then we get the div with querySelector and pass it into the isEllipsisActive .

So the console log should log true since we truncated the text with the CSS.

Conclusion

We can check if a piece of text is truncated with the CSS text-overflow property by checking whether the offsetWidth of the element is less than its scrollWidth .

Categories
JavaScript Answers

How to Reload a Page Every 5 Seconds with JavaScript?

Sometimes, we want to reload a page every 5 seconds in our web app.

In this article, we’ll look at how to reload a page every 5 seconds with JavaScript.

Using the setInterval Function

We can use the setInterval function to run code periodically.

It takes the callback with the code to run periodically as the first argument and the 2nd argument is the delay between each time the callback runs.

For instance, if we have:

<div>
  hello world
</div>

Then we can write:

setInterval(() => {
  window.location.reload();
}, 5000);

to call window.location.reload event 5 seconds.

The delay is in milliseconds so 5000 ms is 5 seconds.

Now we should see the page reload every 5 seconds.

Conclusion

We can use the setInterval function to run code to reload the page periodically.

window.location.reload() will reload the page.

Categories
JavaScript Answers

How to Scroll to the Top of a Browser Page with JavaScript?

Sometimes, we may want to scroll to the top of a browser page with JavaScript.

In this article, we’ll look at how to scroll to the top of a browser page with JavaScript.

Use the window.scrollTo Method

We can use the window.scrollTo method with the x and y coordinates to scroll to as arguments respectively.

For instance, if we have the following HTML:

<div>

</div>
<button>
  scroll to top
</button>

Then we can write the following JavaScript to add child elements to the div and make the button scroll to the top of the page by writing:

const button = document.querySelector('button')
const div = document.querySelector('div')
for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

button.addEventListener('click', () => {
  window.scrollTo(0, 0);
})

We have the for loop to add elements with document.createElement .

And then we set the textContent to some content.

Then we call appendChild to add the elements.

Next, we call button.addEventListener with 'click' to add a click listener.

We call scrollTo with 0 and 0 to scroll to the top of the page.

So when we click on ‘scroll to top’, we should go to the top of the page.

We can also change the scroll behavior with an object to change the scroll behavior.

For instance, we can write:

button.addEventListener('click', () => {
  window.scrollTo({
    top: 0,
    behavior: `smooth`
  })
})

top is set to 0 to scroll to the top.

behavior is set to 'smooth' to make the scrolling smooth.

Conclusion

We can scroll to the top of the page with the window.scrollTo method.

Categories
JavaScript Answers

How to Adjust the Width of an Input Field to the Width of its Input Value?

Sometimes, we may want to adjust the width of an input field to the width of its input value.

In this article, we’ll look at how to adjust the width of an input field to the width of its input value.

Listen to the keypress Event

We can listen to the keypress event to get the input value on keypress.

Then we can set the style.width property of the input to the width of the input value.

To do this, we write the following HTML:

<input type="text">

And the following JavaScript:

const input = document.querySelector('input')
input.addEventListener('keypress', (e) => {
  input.style.width = `${e.target.value.length}ch`
})

We get the input element with querySelector .

Then we call addEventListener with 'keypress’ to listen to the keypress event.

In the event handler callback, we set input.style.width to the e.target.value.length with unit in ch .

e.target.value has the value inputted into the input box.

ch is the width of the 0 character of the element’s font.

Now when we type in the input, we should see the input box lengthen to the width of the input value as we type stuff in.

Conclusion

We can set an input element’s width to the width of the inputted value setting the width of the input in ch .