Categories
JavaScript Answers

How to Add a Div Element to the Body or Document with JavaScript?

Oftentimes, we want to add a div element to the body or document of the web page with JavaScript.

In this article, we’ll look at how to add a div element to the body or document with JavaScript.

Set the document.body.innerHTML Property

One way to add a div element to the body element is to set the document.body.innerHTML property.

For instance, we can write:

document.body.innerHTML += '<div>hello world</div>';

We assign the innerHTML to a string with the code for a div element.

Therefore, we’ll see the div rendered in the body.

Call the document.createElement Method

Another way to add a div to the body element is to use the document.createElement method.

document.createElement is used to create the div.

Then we call document.body.appendChild to append it to the body element as its child.

For instance, we can write:

const elem = document.createElement('div');  
elem.style.cssText = 'position: absolute; width: 100ppx; height: 100px; z-index:100; background: lightgreen';  
elem.innerHTML = 'hello world'  
document.body.appendChild(elem);

We call document.createElement to create the div.

Then we set the elem.style.cssText property to add some styles to the div with CSS.

Next, we assign a value to the innerHTML property to add some content in the div.

And finally, we call document.body.appendChild with elem to add the div to the body as its child.

Conclusion

We can add a div into the body element of a web page by assigning an HTML string to the document.body.innerHTML property.

Or we can create a div element with document.createElement and call document.body.appendChild with the created div.

Categories
JavaScript Answers

How to Change the Content of a textarea Element with JavaScript?

Sometimes, we want to change the content of a text area element with JavaScript.

In this article, we’ll look at how to change the content of an HTML text area element with JavaScript.

Change the value Property of the Text Area Element

We can change the content of a text area by setting the value of the value property of a text area element.

For instance, if we have the following HTML:

<textarea></textarea>

Then we can set the content of the text area by writing:

document.querySelector('textarea').value = 'hello world';

We select the text area with the document.querySelector method.

Then we assign a value to the value property of the text area.

Therefore, now we should see a text area with ‘hello world’ as the content.

Change the innerHTML Property of the Text Area Element

Another property of the text area element that we can change to add content to the text area element is the innerHTML property.

For instance, if we have the following HTML:

<textarea></textarea>

Then we can set the content of the text area by writing:

document.querySelector('textarea').innerHTML = 'hello world';

We select the text area with the document.querySelector method.

Then we assign a value to the innerHTML property of the text area.

Therefore, now we should see a text area with ‘hello world’ as the content also.

Select a Text Area in a Form from the document.forms Property

If our text area is in a form element, then we can get the text area by the name property of the text area in the form.

For example, if we have the following form:

<form name="form">  
  <textarea name="textarea" rows="10" cols="60"></textarea>  
</form>

Then we can assign the value property of the text area in the form by writing:

document.forms.form.textarea.value = 'hello world';

form and textarea are values of the name attribute for the form and textarea elements respectively.

And so we should see ‘hello world’ in the text area.

Conclusion

We can get the text area with querySelector or document.forms if it’s in a form.

Then we can assign a value to the innerHTML or value property to change its content.

Categories
JavaScript Answers

How to Get the Number of Seconds Since Epoch in JavaScript?

Sometimes, we want to get the number of seconds since the Unix epoch, which is January 1, 1970 midnight UTC.

In this article, we’ll look at how to get the number of seconds since the Unix epoch with JavaScript.

Use the Date.prototype.getTime Method

The JavaScript date’s getTime method returns the Unix timestamp in milliseconds.

Therefore, we can use that to get the number of seconds since the Unix epoch by dividing the returned number by 1000.

We also need to round the result to the nearest integer.

For instance, we can write:

const d = new Date(2021, 1, 1);  
const seconds = Math.round(d.getTime() / 1000);  
console.log(seconds)

We create the d date that we want to get the number of seconds since the Unix epoch from.

To get the number of seconds since the Unix epoch, we call getTime on d .

Then we divide that by 1000.

And then we call Math.round to round the number.

Then we get that seconds is 1612166400.

Conclusion

We can get the number of seconds since the Unix epoch by using the getTime method to return the timestamp in milliseconds.

Then we convert the returned timestamp in seconds by dividing it by 1000.

Categories
JavaScript Answers

How to Get the Difference in Months Between Two Dates in JavaScript?

Sometimes, we want to get the difference in months between 2 dates in our JavaScript code.

In this article, we’ll look at how to get the difference between 2 dates in months with JavaScript.

Get the Month Difference Between the 2 Dates

We can calculate the month difference between 2 dates, then get the month difference based on the year difference.

Then we multiply the year difference by 12 to convert that to months.

Then we subtract the month from the start date.

And then we add the month from the end date.

To do this, we write:

const monthDiff = (d1, d2) => {
  let months;
  months = (d2.getFullYear() - d1.getFullYear()) * 12;
  months -= d1.getMonth();
  months += d2.getMonth();
  return months <= 0 ? 0 : months;
}

const start = new Date(2020, 1, 1)
const end = new Date(2020, 5, 1)
console.log(monthDiff(start, end))

We first get the year difference and convert that to months with:

months = (d2.getFullYear() - d1.getFullYear()) * 12;

Then we subtract the month of d1 with:

months -= d1.getMonth();

Then we add the months from d2 with:

months += d2.getMonth();

And then we return months if it’s bigger than 0.

Otherwise, we return 0.

Therefore, the console log should log 4 since there’s a 4-month difference between the 2 dates.

Conclusion

We can get the difference between the 2 dates by getting the year difference, converting that to months.

Then we can subtract the number of months from the start dates.

And add the months from the end date to remove double counting.

Categories
JavaScript Answers

How to Detect When the User Presses the Shift+Enter and Key Combo and Add a New Line in Text Area When the User Does So?

Sometimes, we want to detect when the user presses the shift-enter key combo and adds a new line in the text area when the user does so.

In this article, we’ll look at how to detect the shift-enter key combo when it’s pressed when the cursor is in the text area.

Add the Text Selection in the Text Area to Move the Cursor

We can move the cursor in the text area to the next line by adding a selection range into the text area.

For instance, if we have the following text area:

<textarea></textarea>

Then we can listen to the keydown event to detect the shift+enter key combo press.

If the combo is pressed, then we stop the default behavior and then add the text selection to the text area to move the cursor to the next line.

To do this, we write:

const pasteIntoInput = (el, text) => {
  el.focus();
  if (typeof el.selectionStart === "number" &&
    typeof el.selectionEnd === "number") {
    const val = el.value;
    const selStart = el.selectionStart;
    el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);
    el.selectionEnd = el.selectionStart = selStart + text.length;
  } else if (typeof document.selection !== "undefined") {
    const textRange = document.selection.createRange();
    textRange.text = text;
    textRange.collapse(false);
    textRange.select();
  }
}

const handleEnter = (evt) => {
  if (evt.keyCode === 13 && evt.shiftKey) {
    if (evt.type === "keypress") {
      evt.preventDefault();
      pasteIntoInput(evt.target, "\n");
    }
  }
}

const textarea = document.querySelector('textarea')
textarea.addEventListener('keydown', handleEnter)

We have the pasteIntoInput function that takes the el element and the text value.

In the function, we call el.focus to focus on the element.

Then we check if selectionStart and selectionEnd if a number.

Then we set the el.value to the combination of the selection of the first part of the text, the concatenate that with the text and the concatenate that with the second part of the selected text.

Then we set el.selectionEnd to the new length of the text.

If documebt.selection is undefined ,

Then we create a new selection with documenbt.selection.createRange .

And then we set the selected text, all collapse to collapse the selection and call select to select it.

Next, we create the handleEnter function which is the event handler.

We detect the shift+enter key combo and stop the default behavior and call pasteIntoInput to paste a new line into the text area if the key combo is pressed.

And finally, we select the text area with querySelector .

And then we call addEventListener to listen for the keydown event on the texta area.

Now when we press shift+enter, the cursor will move to a new line.

Conclusion

We can insert a new line into the text area when shift+enter is pressed by stopping the default behavior and then add a new line character to the selected text and set that as the new value of the text area to add the new line.