Categories
JavaScript Answers jQuery

How to Trigger an Event When Clicking Outside an Element with jQuery?

Sometimes, we want to trigger an event when clicking outside the element with jQuery.

In this article, we’ll look at how to trigger an event when clicking outside the element with jQuery.

Trigger Event When Clicking Outside an Element with jQuery

To trigger an event when clicking outside the element with jQuery, we can listen to the click event on the html element.

Then in the event handler, we can check which element is clicked.

For instance, we write:

<div id='your-div-id'>
  hello world
</div>

to add a div and we want to detect whether we clicked outside of it.

Then we write:

$('html').click((e) => {
  if (e.target.id !== 'your-div-id' && $(e.target).parents('#your-div-id').length === 0) {
    console.log('clicked outside')
  }
});

to select the html element with $('html').

Then we call click on it with the click event listener.

We get the element we clicked on with the e.target property.

So if its id isn’t 'your-div-id' and its parent elements also don’t contain the div with ID your-div-id as returned by the parents method, then we know we clicked outside the div with ID your-div-id.

Therefore, when we click outside the div we added, we see 'clicked outside' logged in the console.

Conclusion

To trigger an event when clicking outside the element with jQuery, we can listen to the click event on the html element.

Then in the event handler, we can check which element is clicked.

Categories
JavaScript Answers

How to Exclude a Route from Running an Express Middleware?

Sometimes, we want to exclude a route from running an Express middleware.

In this article, we’ll look at how to exclude a route from running an Express middleware.

Exclude a Route from Running an Express Middleware

To exclude a route from running an Express middleware, we can create our own function that accepts a route path and middleware function and returns a middleware function that checks the route path before running the middleware function.

For instance, we write:

const express = require('express')
const app = express()
const port = 3000

const unless = (path, middleware) => {
  return (req, res, next) => {
    if (path === req.path) {
        return next();
    } else {
        return middleware(req, res, next);
    }
  };
};

const middleware = (req, res, next)=>{
  console.log('middleware')
  next()
}

app.use(unless('/exclude', middleware));

app.get('/', (req, res) => {
  res.send('hello world')
});

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

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

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We create the unless function that takes the path route path string and the middleware middleware function.

In the function, we return a function that checks if the request path which is stored in req.path is the same as path.

If it is, then we call next and stop running the function with return.

Otherwise we use return and call middleware to run the middleware function.

Now if we make a request to any route other than /exclude, we see 'middleware' logged.

Conclusion

To exclude a route from running an Express middleware, we can create our own function that accepts a route path and middleware function and returns a middleware function that checks the route path before running the middleware function.

Categories
JavaScript Answers

How to Get Duplicate Values from an Array with Lodash?

Sometimes, we want to get duplicate values from an array with Lodash.

In this article, we’ll look at how to get duplicate values from an array with Lodash.

Get Duplicate Values from an Array with Lodash

To get duplicate values from an array with Lodash, we can use the countBy method to count the values.

Then we call the JavaScript array’s reduce method to get all the items that has count more than 1 and put them in an array.

For instance, we write:

const items = [1, 1, 2, 3, 3, 3, 4, 5, 6, 7, 7];

const dup = Object.entries(_.countBy(items))
  .reduce((acc, [key, val]) => {
    return val > 1 ? acc.concat(key) : acc
  }, [])
  .map(Number)

console.log(dup)

We call the countBy method with items to return an object with the count of each item in the items array.

Then we call Object.entries to return an array of key-value pairs in the object returned by countBy.

Next, we call reduce with a callback that takes the acc array and the destructured key and val from the each array returned by Object.entries.

If val is bigger than 1, then we know there’s more than one item with the given key.

So we put the in acc with concat.

Otherwise, we return acc without appending the entry since there’s only one instance of the val value.

We pass in an empty array as the value of the 2nd argument so acc is initialized to an empty array.

Finally, we call map with Number to convert all the entries back to numbers.

Therefore dup is [1, 3, 7] according to the console log.

Conclusion

To get duplicate values from an array with Lodash, we can use the countBy method to count the values.

Then we call the JavaScript array’s reduce method to get all the items that has count more than 1 and put them in an array.

Categories
JavaScript Answers

How to Clear a Text Area on Focus with JavaScript?

Sometimes, we want to clear a text area on focus with JavaScript.

In this article, we’ll look at how to clear a text area on focus with JavaScript.

Clear a Text Area on Focus with JavaScript

To clear a text area on focus with JavaScript, we can call the jQuery focus method with a callback that sets the value of the text area to an empty string.

For instance, we write:

<textarea></textarea>

to add a text area.

Then we write:

$('textarea').focus(function() {
  $(this).val('');
});

We select the text area with $('textarea').

Then we call focus with a callback that sets the text area’s value to an empty string by writing:

$(this).val('');

Conclusion

To clear a text area on focus with JavaScript, we can call the jQuery focus method with a callback that sets the value of the text area to an empty string.

Categories
JavaScript Answers

How to Convert a JavaScript Object into a Key-Value Object Array?

Sometimes, we want to convert a JavaScript object into a key-value object array.

In this article, we’ll look at how to convert a JavaScript object into a key-value object array.

Convert a JavaScript Object into a Key-Value Object Array

To convert a JavaScript object into a key-value object array, we can use the Object.entries method to return an array with of key-value pair arrays of a given object.

Then we can use the JavaScript array map method to map the key-value pair arrays into objects.

For instance, we write:

const data = {
  firstName: 'John',
  lastName: 'Doe',
  email: 'doe@gmail.com'
}
const output = Object.entries(data).map(([key, value]) => ({
  key,
  value
}));

console.log(output);

to call Object.entries with data to return an array of key-value pair arrays in the data object.

Then we call map with a callback that destructures the key and value from the parameter, put them in an object as properties, and then return the object.

Therefore, output is:

[
  {
    "key": "firstName",
    "value": "John"
  },
  {
    "key": "lastName",
    "value": "Doe"
  },
  {
    "key": "email",
    "value": "doe@gmail.com"
  }
]

according to the console log.

Conclusion

To convert a JavaScript object into a key-value object array, we can use the Object.entries method to return an array with of key-value pair arrays of a given object.

Then we can use the JavaScript array map method to map the key-value pair arrays into objects.