Categories
JavaScript Tips

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

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.

Categories
JavaScript Tips

JavaScript Tips — Removing Options, Create Random Tokens, and More

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.

Secure Random Token in Node.js

We can generate a secure random token easily with Node.js.

For instance, we can write:

require('crypto').randomBytes(48, (err, buffer) => {
  const token = buffer.toString('hex');
});

We import the crypto library and call its randomBytes method.

It calls the callback with a buffer which we can convert to a hex string.

Perform .join on a Value in an Array of Objects

We can call join on a value in an array of objects if we call map to get the values first,

For instance, if we have:

const students = [
  { name: "james", age: 12 },
  { name: "alex", age: 14 },
  { name: "mary", age: 11 }
]

Then we can use map and join by writing:

students.map(s => s.name).join(",");

We get the name property of each object in the array and call join to join them with a comma.

Split String Only on First Instance of Specified Character and Get the Substring After it

We can use capturing parentheses in our regex that we use with split .

For instance, we can write:

"foo_bar_baz".split(/_(.+)/)[1]

This pattern will only capture the first underscore.

_.+ means the underscore and everything after it.

Then we get 'bar_baz' returned from it.

We can also use substring and indexOf to do the same thing.

For example, we can write:

`const str = "foo_bar_baz";
`const newStr = str.substring(str.indexOf('_') + 1);

indexOf gets the index of the first instance of _ , then we add 1 to get the rest of the string.

Resolve Promises One After Another

To resolve promises one after another, we can write an async function.

For instance, we can write:

async function writeFiles(texts) {
  for(const text of texts) {
    await writeFile(text);
  }
};

We can use async and await with the for-of loop to write files.

writeFile is a function that returns a promise.

Also, we can promisify existing async calls in Noe apps.

We can use Bluebird to do that:

const Promise = require("bluebird");
const fs = Promise.promisifyAll(require("fs"));

const readAll = Promise.resolve(files).map(fs.readFile,{ concurrency: 1 });

readAll.then((allFileContents) => {
    // do stuff to read files.
});

We convert the fs.readFile method to a promise so we can call then on it to chain them.

Get a URL without the Query String

To get a URL without the query string part, we can use the split method.

For instance, we can write:

window.location.href.split('?')[0]

We call split with the question mark and get the first part.

Also, we can write:

const url = `${location.origin}${location.pathname}${location.hash}`;

to get all the parts before the query string and concatenate them together.

location.origin gets us the domain part of the URL.

location.pathname gets the path of the IRL.

And location.hash gets the hash part.

Remove Time from Date with Moment.js

To remove time from a date with moment.js, we can call format to format a date string.

For example, we can write:

moment().format('LL');

We can also use:

moment().startOf('day')

to get the day.

Removing an Item from a Select Box

We can remove an item from a select box by using the jQuery.

For instance, if we have the given select element:

<select name="fruit" id="fruit">
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="grape">Grape</option>
</select>

Then we can remove it by writing:

$("#fruit option[value='grape']").remove();

We can remove the option with the value grape by using the selector.

Access iFrame Parent Page Using jQuery

We can pass in the second argument to the $ function to specify that we want to access the parent window.

For instance, we can write:

$('#parentEl', window.parent.document).html();

We pass in the window.parent.document value to select the element with ID with parentEl from the parent window instead of the current one.

Conclusion

We can use the crypto module to create a random token.

To call join on a property of objects in the array, we can call map to get the values in an array first.

Also, we can get the URL without a query string by using various properties of the location object.

We can remove an option element by its selector.

Categories
JavaScript Tips

JavaScript Tips — Callbacks, Browser Versions, and Context Menu

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.

Pass an Array as Functions Arguments

There are 2 ways to pass an array as function arguments in JavaScript.

One way is to use the apply method.

For instance, we can write:

const args = ['foo', 'bar', 'baz'];
fn.apply(this, args);

We pass in args in as the arguments of fn .

Also, we can use the spread syntax for spreading array entries as function arguments:

fn(...args);

Passing Parameters to a Callback Function

We can pass parameters to a callback function by using the rest parameter syntax.

For instance, if we have:

const callback = (param1, param2) => {
  console.log(param1, param2);
}

const foo = (callback, ...args) => {
  callback(args[1], args[2]);
}

foo(callback, "hello", "world");

We have a callback function that takes 2 parameters.

Then we have a foo function that takes a callback and other arguments.

args is an array of the arguments after the first one.

Then we can call foo with the callback function and the arguments after it.

Then we can use the arguments with the callback .

Add a Custom Right-Click Menu to a Webpage

We can create a custom context menu by listening to the contextmenu event.

For instance, we can write:

document.addEventListener('contextmenu', (e) => {
  alert("opened context menu");
  e.preventDefault();
}, false);

We call e.preventDefault to prevent the default action so nothing else runs after the alert is displayed.

Now when we right-click on the page, we should see the alert displayed.

How to Get Object Length

We can get the length of the object by using the Object.keys method.

For example, we can write:

Object.keys(obj).length;

to get the length of object obj .

Simulate a Click with JavaScript?

We can simulate a click with JavaScript by using the Event constructor.

For instance, we can write:

const clickEvent = new Event('click');
elem.dispatchEvent(clickEvent);

We created the clickEvent with the Event constructor by passing the string 'click' to it.

Then we call dispatchEvent to trigger the click event on the element elem .

Get a URL Parameter in Express

To get a URL parameter in Expression, we can use the req.params property.

For instance, we can write:

app.get('/tags/:tagId', (req, res) => {
  res.send(req.params.tagId);
});

to get the tagId URL parameter.

If we want to get a query string parameter, we can use the req.query property.

For example, we can write:

app.get('/tags', (req, res) => {
  res.send(req.query.tagId);
});

Then we if we have ?tagId=1 , then req.query.tagId would be 1.

Clearing All Cookies with JavaScript

We can clear all cookies with JavaScript by splitting the document.cookies string by the semicolon.

Then we can loop through each entry to set the expiry date to the past.

For instance, we can write:

const cookies = document.cookie.split(";");

for (const cookie of coookies) {
  const eqPos = cookie.indexOf("=");
  const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
  document.cookie = `%{name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT`;
}

After we split the cookie by the semicolon, we loop through each entry.

In the loop body, we get the position of the equal sign.

Then we get the name by taking the part before the equal sign.

Then we set the cookie with expires set to the old expiry date.

It won’t delete with the HttpOnly flag set.

And it won’t delete cookies that have been set with the Path value.

Detect the Version of a Browser

We can detect the version of the browser the user is using with the bowser library.

To use it, we add the following script tag:

<script src="https://unpkg.com/bowser@2.4.0/es5.js"></script>

Then we can write:

if (bowser.msie && bowser.version <= 10) {
  console.log('using old IE');
}

msie checks if a user is using IE and version checks if it’s less than or equal to 6.

There’s also a module version, which we can use by writing:

import * as Bowser from "bowser";

It can parse other parts of the user agent and get information from it.

Conclusion

We can pass arguments from an array in a few ways.

There are libraries to help us check for IE easier.

Get URL parameters is easy with Express.

We can pass arguments to callbacks.

The contextmenu event is emitted if we right-click.

Categories
JavaScript Tips

JavaScript Tips — Prepend Array Values, Checking Existence, and More

As with any kind of app, there are difficult issues to solve when we write apps for JavaScript. In this article, we’ll look at some solutions to common JavaScript problems.

Most Efficient Way to Prepend a Value to an Array

We can prepend a value to an array by using the unshift method.

For instance, we can write:

const a = ['foo', 'bar', 'baz'];
a.unshift('qux');

Then a is now [“qux”, “foo”, “bar”, “baz”] .

Also, we can use the spread operator do to the same thing.

For instance, we can write:

const a = ['foo', 'bar', 'baz'];
const b = ['qux', ...a];

Then b is [“qux”, “foo”, “bar”, “baz”] .

How do I Check Whether an Array Contains a String

We can check if an array contains a string with the includes or indexOf methods.

For example, we can write:

arr.indexOf('foo') > -1

or:

arr.includes('foo')

to check if arr has the string 'foo' .

indexOf returns -1 if the element isn’t in the array and the index otherwise.

includes returns true if the element is in the array and false otherwise.

If we have an array of objects, then we can use find , some , or filter .

For instance, if we have:

const arr = [{ name: 'foo' }, { name : 'bar' }, { name: 'baz' }];

Then we can write:

arr.find(a => a.name === 'bar')

to find the first element in arr that has the name property equal to 'bar' .

It’ll return the element if it’s there and undefined otherwise.

Also, we can call some to do the same check:

arr.some(a => a.name === 'bar')

some returns true if the condition is met and false otherwise.

We can also use filter :

arr.filter(a => a.name === 'bar')

It returns an array with the entries that meet the condition if those elements exist and an empty array otherwise.

Display “Are you sure you want to navigate away from this page?” Message When Changes Committed

To show a message before the user navigates away from a page, we can listen to the beforeunload event.

For instance, we can write:

window.onbeforeunload = () => {
  return `true;
}`

Then we should see a confirmation box asking the user if they want to navigate away from the page.

We return true since any custom messages are ignored and the browser’s own message is displayed.

For instance in Chrome, it would display ‘Changes you made may not be saved’.

Find the Width of a div using Vanilla JavaScript

To find the width of a div using plain JavaScript, we can use the offsetWidth property to do that.

For instance, we can write:

document.getElementById("div").offsetWidth

The width includes the borders.

If we don’t want to include the width of the border, we can write:

document.getElementById("div").clientWidth;

And we can get the assigned width with:

getComputedStyle(document.getElementById("div")).width;

Display a Confirmation Dialog when Clicking on an <a> Link

To display a confirmation box with we click on a link, we can get the a element, then we can attach a click listener to it.

For instance, given the following HTML code:

<a class="confirmation">Link</a>

Then we can write:

const confirmation = document.querySelector('.confirmation');
const onClick = (e) => {
  if (!confirm('Are you sure?')){
    e.preventDefault();
  }
};

confirmation.addEventListener('click', onClick, false);

We called addEventListener to attach the onClick listener to our anchor element.

In the listener function, we display a confirm dialog box with confirm .

Then the user clicks cancel, then we call preventDefault() to stop whatever the default action is.

Check if Type is Boolean

We can check if a variable is a boolean with the typeof operator.

For instance, we can write:

typeof variable === "boolean"

Now we check if variable is a boolean with that.

Disabled Clicks on a Tag

To disable clicks on the tag with JavaScript, we can set the href with JavaScript code disable clicks.

For instance, we can write:

<a href="javascript:() => { return false; }">disabled link</a>

or:

<a href="/" onclick="return false;">disabled link</a>

or:

<a href="javascript:void(0)">disabled link</a>

void always returns undefined .

All 3 pieces of code do the same thing.

Conclusion

There are a few ways to disable the link. We can get an element width with various properties. Adding items in arrays can be done with the spread operator and unshift . There are many ways to check for the existence of elements in an array.

Categories
JavaScript Tips

JavaScript Tips — Checking File Sizes, Modular Arithmetic and More

As with any kind of app, there are difficult issues to solve when we write apps for JavaScript. In this article, we’ll look at some solutions to common JavaScript problems. Replace Multiple Characters in One Replace Call

We can use the g flag on the regex to replace multiple characters with one replace call.

For instance, we can write:

string.replace(/_/g, ' ').replace(/#/g, '')

We replace all instances of _ with the first call.

Then we replace all instances of # with the 2nd call.

Make the Window Full Screen with Javascript

We can use the fullscreen API to make a window full screen.

For example, we can write:

document.documentElement.`requestFullscreen();`

We just call the requestFullScreen method to change the window to full-screen mode.

Then we can call document.exitFullScreen to exit full-screen mode.

The Fastest Way to Convert JavaScript NodeList to Array

We can convert a JavaScript NodeList to an array with the spread operator or the Array.from method.

For example, we can write:

const els = Array.from(document.querySelectorAll('p'));

We can use the spread operator by writing:

const els = [...document.querySelectorAll('p')];

Capitalize the First Letter of Each Word

We can capitalize the first letter of each word with some array methods.

For instance, we can write:

str = str.toLowerCase()
  .split(' ')
  .map((s) => `${s.charAt(0).toUpperCase()}${s.substring(1)}`)
  .join(' ');

We convert the string to lower case first, then we split the words with split .

Then we call map to match each word to have the first letter upper case and the rest lower case.

Finally, we call join to join the words back together.

JavaScript File Upload Size Validation

We can validate the size of the file without using any library.

For example, we can write:

<input onchange="validateSize(this)" type="file">

Then we can write:

const validateSize = (file) => {
  const fileSize = file.files[0].size;
  if (fileSize > 2 * (1024 ** 2)) {
    console.log('File size exceeds 2 MB');
  } else {
    //...
  }
}

We just get the file.files[0].size property to validate the size of the first file selected.

file is the file input.

files has one or more selected files.

size has the size.

Add a class to a DOM Element

To add a class to a DOM element, we can use the classList property’s add method.

For example, we can write:

const element = document.querySelector('div');
element.classList.add('baz');

We get the div element, then we can use the add method of the classList to add the class name.

Using % to do Modular Arithmetic

The % operator is used for getting the remainder of one number divided by another.

But we can also use it to get the one number mod another number.

For instance, we can write:

const mod = (m, n) => `((m % n) + n) % n;`

We first get the remainder of m divided by n .

Then we add n to it to make it positive.

Finally, we get the remainder of that value divided by n .

Most Efficient Way to Concatenate N Arrays

We can concatenate one or more arrays with the push method.

To do that, we can write:

arr.push(...a, ...b)

Then all the items from a and b will be appended to arr .

We can also use concat with multiple arrays.

For instance, we can write:

arr = arr.concat(array, array1, array2, array3);

We call concat so that we put the entry of each array into a new array after the entries of arr .

Then that array is returned.

Therefore, we’ve to assign it to arr to update it with the returned value.

Find an Element in the DOM Based on an Attribute Value

We can find an element in the DOM based on an attribute value.

For instance, we can write:

const fileInput = document.querySelector("input[type=file]");

We get a file input by using querySelector .

It takes any CSS selector, including attribute selectors.

type is the attribute, file is the value.

We can also get a group of elements with the same selector by using querySelectorAll .

Conclusion

replace can be chained so we can replace more than one kind of text. A NodeList can be converted to an array with Array.from or the spread operator. We can concatenate arrays with push or concat. % can be used to do modular arithmetic if we combine it with other operations. File sizes can be checked on the client-side.