Categories
Vue Answers

How to Detect Clicks Outside an Element with Vue.js?

Sometimes, we want to detect clicks outside an element with Vue.js.

In this article, we’ll look at how to detect clicks outside an element with Vue.js.

Detect Clicks Outside an Element with Vue.js

We can detect clicks outside an element with Vue.js by creating our own directive.

For instance, we can write:

<template>
  <div id="app" style="width: 500px; height: 500px">
    <div v-click-outside="onClickOutside">hello world</div>
  </div>
</template>

<script>
import Vue from "vue";

Vue.directive("click-outside", {
  bind(el, binding, vnode) {
    el.clickOutsideEvent = (event) => {
      if (!(el === event.target || el.contains(event.target))) {
        vnode.context[binding.expression](event);
      }
    };
    document.body.addEventListener("click", el.clickOutsideEvent);
  },
  unbind(el) {
    document.body.removeEventListener("click", el.clickOutsideEvent);
  },
});

export default {
  name: "App",
  methods: {
    onClickOutside() {
      console.log("clicked outside");
    },
  },
};
</script>

We call Vue.directive with the directive name and an object that has the bind and unbind methods to add the el.clickOutsideEvent method in the bind method.

In clickOutsideEvent , we check if el isn’t event.target and that it doesn’t contain event.target .

If both are true , then we add vnode.context[binding.expression](event); to run the method that we set as the value of the v-click-outside directive.

Then we call document.body.addEventListener to add a click event listener to run clickOutsideEvent .

In the unbind method, we remove the event listener with removeEventListener when we unbind the directive.

Then in the template, we add v-click-outside and set the value of it to onClickOutside to run the method when we click outside.

When we click outside, we should see 'clicked outside' logged.

Conclusion

We can detect clicks outside an element with Vue.js by creating our own directive.

Categories
React Answers React Projects

How to Create a Countdown Timer with React?

Sometimes, we want to create a countdown timer with React.

In this article, we’ll look at how to create a countdown timer with React.

Create a Countdown Timer with React

We can create a countdown timer by creating a timer component that updates the remaining time regularly.

To do this, we write:

import React, { useEffect, useState } from "react";

const Timer = (props) => {
  const { initialMinute = 0, initialSeconds = 0 } = props;
  const [minutes, setMinutes] = useState(initialMinute);
  const [seconds, setSeconds] = useState(initialSeconds);
  useEffect(() => {
    const myInterval = setInterval(() => {
      if (seconds > 0) {
        setSeconds(seconds - 1);
      }
      if (seconds === 0) {
        if (minutes === 0) {
          clearInterval(myInterval);
        } else {
          setMinutes(minutes - 1);
          setSeconds(59);
        }
      }
    }, 1000);
    return () => {
      clearInterval(myInterval);
    };
  });

  return (
    <div>
      {minutes === 0 && seconds === 0 ? null : (
        <h1>
          {minutes}:{seconds < 10 ? `0${seconds}` : seconds}
        </h1>
      )}
    </div>
  );
};

export default function App() {
  return (
    <>
      <Timer initialMinute={5} initialSeconds={0} />
    </>
  );
}

We create the Timer component that takes the initialMinute and initialSeconds props that sets the initial time.

Then we use the useState prop to create the minutes and seconds state.

Next, we call the useEffect hook with a callback that creates a timer with setInterval .

The timer runs every second.

The setInterval callback checks if the seconds is bigger than 0 and calls setSeconds to decrease the seconds.

If seconds is 0 and minutes is 0, then we call clearInteraval to stop the timer.

Otherwise, we call setMinutes to minutes — 1 and call setSeconds to 59 decrements the minute.

Then we return a callback that calls clearInterval to clear the timer.

Below that, we render the minutes and seconds onto the screen.

If seconds is less than 10 then we add a 0 in front of it.

Conclusion

We can create a countdown timer by creating a timer component that updates the remaining time regularly.

Categories
React Answers

How to Detect Content Changes in contentEditable Elements in React?

Sometimes, we want to detect content changes in a contenteditable element in our React app.

In this article, we’ll look at how to detect content changes in a contenteditable element in our React app.

Detect Content Changes in contentEditable Elements in React

We can detect content changes in contenteditable elements by listening to the input event.

To do this, we write:

import React from "react";

export default function App() {
  return (
    <>
      <div
        contentEditable
        onInput={(e) => console.log(e.currentTarget.textContent)}
      >
        hello world
      </div>
    </>
  );
}

We pass in a function that logs the e.currentTarget.textContent property that has the text content of the div.

It’ll run as we change the content of the div by editing it.

Conclusion

We can detect content changes in contenteditable elements by listening to the input event.

Categories
React Answers

How to Handle the KeyPress Event in React?

Sometimes, we need to do something when a key is pressed in our React app.

In this article, we’ll look at how to do something when a key is pressed in our React app.

Handle the KeyPress Event in React

We can handle the keypress event when a key is pressed in React by setting the onKeyPress prop to an event handler function.

For instance, we can write:

import React from "react";

export default function App() {
  const handleKeyPress = (event) => {
    if (event.key === "Enter") {
      console.log("enter press here! ");
    }
  };
  return (
    <>
      <input type="text" onKeyPress={handleKeyPress} />
    </>
  );
}

We have the handleKeyPress function that takes the event object as a parameter.

The event object has the key property which is set to the string with the key name that’s pressed.

Therefore, we can use it to check if the enter key is pressed by checking aginst the event.key property.

When enter is pressed in the input, the console log will run.

Conclusion

We can handle the keypress event when a key is pressed in React by setting the onKeyPress prop to an event handler function.

Categories
JavaScript Answers

How to Get Trig Methods to Accept Degrees Instead of Radians in JavaScript?

To get the Math.sin, Math.cos, and Math.tan methods to use degrees instead of radians in JavaScript, we can convert the degree value accepted by Math.sin , Math.cos or Math.tan to radians.

For instance, we can write:

const toRadians = (angle) => {
  return angle * (Math.PI / 180);
}
console.log(Math.sin(toRadians(45)))
console.log(Math.cos(toRadians(45)))
console.log(Math.tan(toRadians(45)))

to create the toRadians function that converts the angle in degrees to radians by multiplying angle in degrees by Math.PI / 180 .

Then we call Math.sin , Math.cos , and Math.tan with toRadians(45) , which converts 45 degrees to radians.

And so we get:

0.7071067811865475
0.7071067811865476
0.9999999999999999

from the console log.