Categories
JavaScript Tips

JavaScript Tips — Callbacks, Browser Versions, and Context Menu

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.

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.

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 *