Categories
JavaScript Answers

How to Render HTML Inside a Text Area with JavaScript?

Sometimes, we want to render HTML inside a text area.

In this article, we’ll look at how to render HTML content inside a text area.

Render Content in a contenteditable Div

An HTML text area can’t render HTML.

However, we can make a div’s content editable with the contenteditable attribute.

Therefore. we can use an editable div as we do with a text area but with HTML content.

For instance, we can write the following HTML:

<div class="editable" contenteditable="true"></div>
<button class="bold">toggle red</button>
<button class="italic">toggle italic</button>

Then we can style it with the following CSS:

.editable {
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
  padding: 5px;
  resize: both;
  overflow: auto;
}

And then we can get the buttons and change the text when we click on them:

const bold = document.querySelector('.bold')
const italic = document.querySelector('.italic')
const editable = document.querySelector('.editable')

const toggleRed = () => {
  const text = editable.innerHTML;
  editable.innerHTML = `<p style="color:red">${text}</p>`;
}

const toggleItalic = () => {
  const text = editable.innerHTML;
  editable.innerHTML = `<i>${text}</i>`;
}

bold.addEventListener('click', toggleRed);
italic.addEventListener('click', toggleItalic);

We make the div editable with the contenteditable attribute set to true .

We select all the elements we added with document.querySelector .

Then we have the toggleRed function that gets the existing innerHTML from the editable div.

Then we add a p element with color style set to red.

Likewise, we have the toggleItalic function to get the innerHTML from the editable div.

Then we wrap the i tag around the text.

The CSS just sets the width, border, padding, and overflow styles for the editable div.

Now when we click on toggle red and toggle italic, we see the corresponding styles applied to the text we typed into it.

Conclusion

We can render HTML in an editable div instead of a text area if we want to add a box where we can edit rich text.

Categories
JavaScript Answers

How to Detect Scroll Direction with JavaScript?

Sometimes, we want to detect scroll direction with JavaScript.

In this article, we’ll look at how to detect scroll direction with JavaScript.

Listen to the scroll Event

We can listen to the scroll event of window to check the scroll direction.

For instance, we can write:

window.onscroll = function(e) {
  console.log(this.oldScroll > this.scrollY);
  this.oldScroll = this.scrollY;
}

to set a scroll event listener to the window.onscroll property.

Then we get the scrollY value and check if it’s bigger than the oldScroll value.

If it’s bigger, that means we’re scrolling down.

Then we set the scrollY value to the oldScroll property so that we can keep the old scroll value.

Both values are in pixels so we can compare them directly.

Listen to the scroll Event and Track the pageYOffset Property

We can also use the pageYOffset property to track the location that we’ve scrolled to vertically.

For instance, we can write:

let oldValue = 0
let newValue = 0
window.addEventListener('scroll', (e) => {
  newValue = window.pageYOffset;
  if (oldValue < newValue) {
    console.log("Up");
  } else if (oldValue > newValue) {
    console.log("Down");
  }
  oldValue = newValue;
});

to add a scroll listener to window with addEventListener .

Then we set newValue to window.pageYOffset .

If newValue is bigger than oldValue , then we scrolled up.

If newValue is smaller than oldValue , then we scrolled down.

In the end, we set newValue to oldValue so we can compare the 2.

Conclusion

We can detect scroll direction with the pageYOffset or the scrollY properties.

Categories
JavaScript Answers

How to Get a String in YYYYMMDD Format From a JavaScript Date Object?

Sometimes, we may want to convert a JavaScript date object to a string in YYYYMMDD format.

In this article, we’ll look at how to format a JavaScript date into a string in YYYYMMDD format.

Using Native JavaScript Date and String Methods

One way to get a JavaScript date into a string in YYYYMMDD format is to use native JavaScript date and string methods.

For instance, we can write:

const date = new Date(2021, 1, 1)
const year = date.getFullYear()
const month = ('0' + (date.getMonth() + 1)).substr(-2)
const day = ('0' + date.getDate()).substr(-2)
const dateStr = [year, month, day].join('')
console.log(dateStr)

We create a date object with the Date constructor with the year, month, and day.

The month’s value is from 0 to 11, where 0 is for January, 1 for February, etc.

Then we can get the year, month, and day from the date.

We call getFullYear to get the 4 digit year.

And we call getMonth to get the month plus 1 to get a human-readable month.

Then we attach string 0 before it and call substr -2 to get the last 2 characters of the string.

And we call getDate to get the date and format it the same way with substr .

Finally, we join the year , month , and day together with join .

Therefore, dateStr is '20210201' .

Date.prototype.toISOString

We can call toISOString to get the date string from a JavaScript date object.

Then we can use string methods to extract the year, month, and date parts and remove the dashes from that part.

For instance, we can write:

const date = new Date(2021, 1, 1)
const dateStr = date.toISOString().slice(0, 10).replace(/-/g, "");
console.log(dateStr)

We call toISOString to get the date string in ISO8601 format.

Then we call slice with 0 and 10 to extract the first part, which has the year, month, and day.

And then we call replace to replace all the dashes with empty strings to remove them.

Therefore, we get the same result for dateStr .

Also, we can replace slice with substring :

const date = new Date(2021, 1, 1)
const dateStr = date.toISOString().substring(0, 10).replace(/-/g, "");
console.log(dateStr)

moment.js

We can also use the moment.js library to format a date easily.

For instance, we can write:

const date = new Date(2021, 1, 1)
const dateStr = moment(date).format('YYYYMMDD');
console.log(dateStr)

We pass in our date to the moment function to create a moment object withn the date.

Then we call format with the format string to format the item.

And so we get the same value for dateStr .

Conclusion

We can format a native JavaScript date into a string with native JavaScript date and string methods.

Or we can use moment.js to format a date.

Categories
JavaScript Answers

How to Get the Number of Days Between Two Dates in JavaScript?

We often have to get the number of days between 2 dates in our JavaScript apps.

In this article, we’ll look at how to get the number of days between 2 dates with JavaScript.

Using String and Date Methods

We can calculate the number of days between 2 dates with JavaScript by using native string and date methods.

For instance, we can write:

const parseDate = (str) => {
  const [month, day, year] = str.split('/');
  return new Date(year, month - 1, day);
}

const datediff = (first, second) => {
  return Math.round((second - first) / (1000 * 60 * 60 * 24));
}

const diff = datediff(parseDate("1/1/2000"), parseDate("1/1/2001"))
console.log(diff)

We have the parseDate function that takes str date string in MM/DD/YYYY format.

We parse it by splitting the date string with '/' as the separator.

Then we get the year , month and day by destructuring.

And we pass all that into the Date constructor to return a date object.

We’ve to subtract month by 1 to get the correct JavaScript month.

Then we calculate the date difference with the dateDiff method by subtracting the second by first .

When we subtract 2 dates, both dates will be converted to timestamps automatically before subtraction.

So we can subtract them directly.

And then we divide this by 1 day in milliseconds.

Finally, we round the division result with Math.round .

Now we can call all the functions we created to parse and get the date difference from the parsed dates.

And so we get diff is 366.

moment.js

We can use moment.js to get the difference between 2 dates easily.

For instance, we can write:

const start = moment("2000-11-03");
const end = moment("2001-11-04");
const diff = end.diff(start, "days")
console.log(diff)

We just pass the date strings into the moment function.

Then we call diff to get the difference between the moment date it’s called on and the moment date object we passed in.

The 2nd argument is the unit of the difference we want to return.

So diff is also 366 since the 2 dates differ by 366 days.

Conclusion

We can use native JavaScript string and date methods to compute the difference between 2 dates.

Also, we can use the moment.js library to make our lives easier.

Categories
JavaScript Answers

How to Format a Floating Point Number in JavaScript?

Oftentimes, we have to format a floating-point number into the format we want in JavaScript.

In this article, we’ll look at how to format a floating-point number into the format we want with JavaScript.

Math.round

We can use Math.round to round a number into the number of decimal places we want by multiplying the original number 10 to the power of the number of decimal places we want to round to.

Then we pass that number into Math.round , and we divide the rounded number by the same number we multiplied the original number with.

For instance, we can write:

const original = 123.456
const result = Math.round(original * 100) / 100;
console.log(result)

We multiply original by 100, which is 10 to the power of 2.

So we round to 2 decimal places.

And we divide by 100.

Then result is 123.46.

This also works if we also round to other numbers of decimal places.

For instance, we can write:

const original = 123.45678
const result = Math.round(original * 1000) / 1000;
console.log(result)

And result is 123.457.

Number.prototype.toFixed

We can call the toFixed method to return a string with the number rounded to the given number of decimal places.

For instance, we can write:

const original = 123.45678
const result = original.toFixed(3)
console.log(result)

Then result is ‘123.457’ .

3 is the number of decimal places to round to.

result is a string instead of number in the previous example.

This is the easier way to format a number to the number of decimal places we want.

Conclusion

We can format a floating-point number into the number of decimal places we want with Math.round or the number’s toFixed method.