Categories
JavaScript Tips

JavaScript Tips — Array for forEach, Getting Styles and Pasted Data

Spread the love

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Change Values of the Array when doing forEach

We can change the values of an array when using forEach .

For instance, we can write:

arr.forEach((part, index, theArray) => {  
  theArray[index] = "foo";  
});

We can access the array itself with the 3rd parameter.

Also, we can set the array as the value of this if we pass it in as the 2nd argument of forEach :

arr.forEach(function(part, index) {  
  this[index] = "foo";  
}, arr);

We’ve to use a regular function instead of an arrow function if we want to access this in the callback.

Get Clipboard Data on Paste Event

To get clipboard data on a paste event, we can listen to the paste event and then get the data with the clipboardData property.

For instance, given that we have the following HTML:

<div id='editableDiv' contenteditable>Paste</div>

We can get the data that’s pasted into the editable div by writing:

const handlePaste = (e) => {  
  e.stopPropagation();  
  e.preventDefault();

  const clipboardData = e.clipboardData || window.clipboardData;  
  const pastedData = clipboardData.getData('Text');  
  console.log(pastedData);  
}

document.getElementById('editableDiv').addEventListener('paste', handlePaste);

We call stopPropgation to stop the propagation of the paste event to parent elements.

And we call preventDefault to stop the default action, which is to paste.

Then we can use the clipboardData property of the event object or window to get the pasted data.

And then we use getData with the 'Text' argument to get the pasted text.

Turn NaN from parseInt into 0 for an Empty String

We can use the || operator to return 0 if NaN is returned from parseInt .

This works because NaN is falsy.

For instance, we can write:

const s = '';  
const num = parseInt(s) || 0;

Get Current Date/Time in Seconds

We can get the current date and time in seconds by using the getTime method and divide by 1000.

For example, we can write:

const seconds = new Date().getTime() / 1000;

We call the getTime method to get the timestamp in milliseconds.

Then we divide by 1000 to convert the timestamp to seconds.

Detect the Enter Key in a Text Input Field

To detect the Enter key in a text input file by listening to the keyup event.

For instance, we can write:

const node = document.querySelector("input");  
node.addEventListener("keyup", (event) => {  
  if (event.key === "Enter") {  
    // ...  
  }  
});

We get the input element and then add a keyup listener to it with addEventListener .

Then we get the key property to get the key that’s pressed.

And we check that against 'Enter' .

Get All CSS Styles Associated with an Element

We can get all CSS styles associated with an element by using the getComputedStyle method.

For instance, we can write:

const stylesObj = document.defaultView.getComputedStyle(element, null);  
const fontFamily = stylesObj["font-family"]

We call getComputedStyle on the document.defaultView object, which has the content of the current tab.

The first argument is the element that we want to get the styles from.

Then we can get the 'font-family' property to get the font family name of font applied to the element.

Change the URL in the Browser without Loading the New Page Using JavaScript

We can use the pushState method to navigate to a new URL without loading a new page.

For instance, we can write:

history.pushState({ foo: "bar" }, "page", "bar.html");

The first argument is a state object, which we can retrieve later.

The 2nd argument is the title, which isn’t used by most browsers.

And the last is the path of the page we want to navigate to.

It’ll save an entry to the browsing history.

If we want to overwrite the existing history entry, we can use replaceState :

`history.`replaceState`({ foo: "bar" }, "page", "bar.html");`

Conclusion

We can use the history API to navigate to a new URL without reloading the tab or window.

Also, we can call getComputedStyle to get all the styles of an element.

We can detect keypresses with the which property.

Also, we can get clipboard data pasted in a contenteditable div.

We can also access the array in the forEach callback in a few ways.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *