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 Create Enums in JavaScript?

Enums are entities that are containers for a list of constants.

There’s no native enum data type in JavaScript.

However, we can create our own JavaScript enums.

In this article, we’ll take a look at how to create enums with JavaScript.

Create an Object with Symbol Values and Freeze it

To create an enum object in JavaScript, we can create an object with symbol property values.

For instance, we can write:

const Colors = Object.freeze({  
  RED: Symbol("Colors.RED"),  
  BLUE: Symbol("Colors.BLUE"),  
  GREEN: Symbol("Colors.GREEN")  
});  
console.log(Colors.RED)  
console.log(Colors.BLUE)  
console.log(Colors.GREEN)

We create an object with the RED , BLUE and GREEN properties.

Then we set their values to symbols.

Symbols are primitive values that can be used as unique identifiers.

We create a symbol with the Symbol function.

Every symbol created with the Symbol function is unique even if we pass in the same argument to the symbol function, so:

Symbol("Colors.RED") === Symbol("Colors.RED")

is false .

We then call Object.freeze on the object to prevent the object from being frozen.

Once an object is frozen, we can’t add or change existing properties in the object.

Then we can access them like we can do within the console log statements.

Conclusion

We can create enums easily with JavaScript by creating an object with symbol values.

Then we can freeze the object with Object.freeze to prevent changes on the object.

Categories
JavaScript Answers

How to Automatically Reload a Page After a Given Period of Inactivity in JavaScript?

Sometimes, we want to automatically reload a page after a given period of inactivity on our web page.

In this article, we’ll look at how to automatically reload a page after a given period of inactivity with JavaScript.

Record the Time When There is Activity

We can listen to the mousemove and keypress events to let us listen for mouse and keyboard activities respectively.

Then we can record the time when the user last used the page in the event listener.

And then we can use that time to calculate how long ago when the user last used the page.

To do this, we write:

let time = new Date().getTime();
const setActivityTime = (e) => {
  time = new Date().getTime();
}
document.body.addEventListener("mousemove", setActivityTime);
document.body.addEventListener("keypress", setActivityTime);

const refresh = () => {
  if (new Date().getTime() - time >= 60000) {
    window.location.reload(true);
  } else {
    setTimeout(refresh, 10000);
  }
}

setTimeout(refresh, 10000);

We have the time variable which has the timestamp in milliseconds as its initial value.

Then we have the setActivityTime event listener which we use to set the time at which the user last used the page.

We listen to the mousemove and keypress events and use setActivityTime as the event listener to record when the user last interacted with the page.

Then we have the refresh function that checks when the user last interacted with the page.

If the time is more than 60 seconds, then we call location.reload to reload the page.

Otherwise, we call refresh again to check again in 10 seconds.

Now the page should refresh if it hasn’t been interacted with for more than 60 seconds.

Conclusion

We can record the latest time of when the user interacted with a page.

Then we can check how long ago was the last page activity and refresh based on the time comparison if required.

Categories
JavaScript Answers

How to Convert Hyphenated Text to Camel Case with JavaScript?

Sometimes, we want to convert strings with hyphenated text to camel case with JavaScript.

In this article, we’ll look at how to convert hyphenated text to camel case with JavaScript.

Use the String.prototype.replace Method

We can use the JavaScript string’s replace method to replace hyphenated text with camel case.

To do this, we find all the substrings that have the hyphen and a letter after it.

Then we replace that with an upper case letter.

For instance, we can write:

const str = 'my-example-setting'
const camelCased = str
  .replace(/-([a-z])/g, (g) => {
    return g[1].toUpperCase();
  });
console.log(camelCased)

We have the str string that we want to convert to camel case.

Then we call replace with a regex that has a hyphen with a letter after it.

The g flag will search for all instance that match the regex pattern.

The 2nd argument of replace is a callback that returns the text that we want to replace what’s in the pattern with.

Therefore, camelCased is ‘myExampleSetting’ .

Lodash camelCase Method

Another way to convert a hyphenated string to a camel-cased string is to use the Lodash camelCase method.

For instance, we can write:

const str = 'my-example-setting'
const camelCased = _.camelCase(str);
console.log(camelCased)

We pass in the string we want to convert as the argument of camelCase .

And we get the same result.

Conclusion

We can use the JavaScript string replace method or the Lodash camelCase method to convert a hyphenated string to a camel-cased string.

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.