Categories
JavaScript Answers

How to Hide or Show Elements with JavaScript?

In many situations, we may want to create components that we can show and hide by toggling them.

In this article, we’ll look at how to hide or show elements with JavaScript.

Hide or Show Elements with JavaScript

We can show or hide elements with JavaScript by setting the style.display property of an element.

We can hide it by setting it to 'none' .

And we can show it by setting it to 'block' .

For instance, we can write the following HTML:

<button>
  toggle
</button>
<p>
  hello world
</p>

Then we can add the following JavaScript code:

const button = document.querySelector('button')
const p = document.querySelector('p')

button.addEventListener('click', () => {
  if (p.style.display === 'none') {
    p.style.display = 'block'
  } else {
    p.style.display = 'none'
  }
})

We add a button and p element with the HTML.

Then we select the elements with document.querySelector .

And then we add a click event listener with the button.addEventListener method.

We check if p.style.display is 'none' .

If it’s 'none' , then we set p.style.display to 'block' .

Otherwise, we set it to 'none' .

'none' makes the element disappear. No space is allocated for the element.

And 'block' makes it display as a block element.

Now when we click on the button, we see the p element being toggled on and off.

Alternatively, we can set the visibility property instead.

The difference between visibility and display is that visibility allocates space for the element no matter if it’s displayed or not.

This isn’t the case with display .

So we can also write:

const button = document.querySelector('button')
const p = document.querySelector('p')

button.addEventListener('click', () => {
  if (p.style.visibility === 'hidden') {
    p.style.visibility = 'visible'
  } else {
    p.style.visibility = 'hidden'
  }
})

And we get the same result in our example.

Conclusion

We can set the display property to 'block' or visibility to 'visible' to show an element.

And we can set the display property to 'none' or visibility to 'hidden' to hide an element.

Categories
JavaScript Answers

How to Add Nested Routes with React Router Version 5?

If we use React to create our JavaScript app, we probably add a routing solution so that we can render different components if we go to different URLs.

React Router is a popular routing library to serve this purpose.

In this article, we’ll look at how to add nested routes with React Router version 5.

Add Nested Routes with React Router Version 5

We can nested routes with React Router version by nesting Route components inside the function we pass into the render prop.

To do this, we write:

import React from "react";
import { BrowserRouter, Route, Link } from "react-router-dom";

const FrontPage = () => <p>front page</p>;
const HomePage = () => <p>home page</p>;
const AboutPage = () => <p>about page</p>;
const Backend = () => <p>back end</p>;
const Dashboard = () => <p>dashboard</p>;
const UserPage = () => <p>user page</p>;

export default function App() {
  return (
    <div>
      <BrowserRouter>
        <Link to="/">front page</Link>
        <Link to="/home">home page</Link>
        <Link to="/about">about page</Link>
        <Link to="/admin">back end</Link>
        <Link to="/admin/home">dashboard</Link>
        <Link to="/admin/users">user page</Link>
        <Route path="/" component={FrontPage} exact />
        <Route path="/home" component={HomePage} />
        <Route path="/about" component={AboutPage} />

        <Route
          path="/admin"
          render={({ match: { url } }) => (
            <>
              <Route path={`${url}/`} component={Backend} exact />
              <Route path={`${url}/home`} component={Dashboard} />
              <Route path={`${url}/users`} component={UserPage} />
            </>
          )}
        />
      </BrowserRouter>
    </div>
  );
}

We have the FrontPage , HomePage , AboutPage , Backend , Dashboard , and UserPage route components.

We’ll use the when we define our routes.

Then in App , we add the BrowserRouter component so we can add the routes inside it.

We add the Link component with the to prop to add links that goes to the given route.

Then we add Route components to map URL paths to components that are passed into the component prop.

The path prop lets us set the path of the route.

exact lets us only load the component when the exact path is matched.

When we go to the URL path given, then the given component will load.

The last Route component has the path set to '/admin' , which is the first part of the URL path.

The render prop is set to a function that takes an object with the match.url property.

We destructure that from the object, then pass them into the Route components we return in the function.

This lets us map route with the path starting with /admin to the given components.

So when we go to /admin , we see the Backend component displayed.

If we go to /admin/home , we see the Dashboard component rendered.

And if we go to /admin/users , we see the UserPage component rendered.

Therefore, when we click on the links, we see the content of each component displayed.

Conclusion

We can add nested routes with React Router 5 easily by nested Route components.

Categories
JavaScript Answers

How to Get the Start and the End of a Day in JavaScript?

Sometimes, we may want to get the start and end of a day with JavaScript.

In this article, we’ll look at ways to get the start and end of a day with JavaScript.

Using Native Date Methods

One way to get the start and end of a day with JavaScript is to use native date methods.

We can use the setHours method to set the hours of a day to the start or end of a day.

For instance, we can write:

const start = new Date(2020, 1, 1, 1, 1);
start.setHours(0, 0, 0, 0);
console.log(start)

We create the start date with the Date constructor.

Then we call setHours with all zeroes to set the time of the date to midnight.

So start is:

Sat Feb 01 2020 00:00:00 GMT-0800 (Pacific Standard Time)

if we’re in Pacific time.

Likewise, we can use setHours to set the hours, minutes, seconds, and milliseconds to the end of the date.

To do this, we write:

const end = new Date(2020, 1, 1, 1, 1);
end.setHours(23, 59, 59, 999);
console.log(end)

to create a date and set it to the end of the date by passing in a few arguments.

23 is the hours.

The first 59 is the minutes.

The second 59 is the seconds.

And 999 is the milliseconds.

Therefore, end is:

Sat Feb 01 2020 23:59:59 GMT-0800 (Pacific Standard Time)

after calling setHours .

Using Moment.js

Alternatively, we can use the moment.js library to return the start and end of a date.

For instance, we can write:

const start = moment(new Date(2020, 1, 1, 1, 1)).startOf('day');
console.log(start.toString())

to create a moment object with the moment function with a JavaScript native date object as its argument.

Then we call startOf with 'day' to return a moment object with the time set to the start of the day.

So we get:

Sat Feb 01 2020 00:00:00 GMT-0800

as the value of start.toString() if we’re in the Pacific time zone.

Likewise, we can use the endOf method to get the end of the date.

To do this, we write:

const end = moment(new Date(2020, 1, 1, 1, 1)).endOf('day');
console.log(end.toString())

We call endOf instead of startOf .

And then end.toString() returns Sat Feb 01 2020 23:59:59 GMT-0800 if we’re in the Pacific time zone.

We can also convert the time zone to UTC before call startOf and endOf with the utc method.

For instance, we can write:

const start = moment(new Date(2020, 1, 1, 1, 1)).utc().startOf('day');
console.log(start.toString())

const end = moment(new Date(2020, 1, 1, 1, 1)).utc().endOf('day');
console.log(end.toString())

to do the conversion.

Then start.toString() returns:

Sat Feb 01 2020 00:00:00 GMT+0000

And end.toString() returns:

Sat Feb 01 2020 23:59:59 GMT+0000

Conclusion

We can get the start and end of a date with JavaScript with native date methods or moment.js.

Categories
JavaScript Answers

How to Get Clipboard Data When We Paste Data into an Element with JavaScript?

Sometimes, we may want to get the clipboard data that we paste into an element in our web app.

In this article, we’ll look at how to get clipboard data when we paste it into our JavaScript app.

Listen to the paste Event

The paste event is triggered when we paste data into an element.

Therefore, we can just listen to that event when our own event listener to get the pasted content.

For instance, we can write the following HTML:

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

Then we can write the following JavaScript code to listen to the paste event:

const handlePaste = (e) => {
  let clipboardData, pastedData;
  e.stopPropagation();
  e.preventDefault();
  clipboardData = e.clipboardData || window.clipboardData;
  pastedData = clipboardData.getData('text/plain');
  console.log(pastedData);
}
const div = document.getElementById('editableDiv')
div.addEventListener('paste', handlePaste);

We create the handlePaste function to get the clipboard data.

First, we call stopPropagation to stop the propagation of the event to the parent and ancestor elements.

Then we call preventDefault to prevent the default paste behavior.

Then we can get the clipboard data from the e.clipboardData or window.clipboardData properties.

Next, we call getData with 'text/plain' to get the pasted text data.

And then we log the pastedData with console log.

Then we select the editable div with the getElementById method.

And we call addEventListener on the div to listen to the paste event.

We can simplify the function by calling e.clipboardData.getData to get the data directly.

Then we can call document.execCommand to do the pasting to the div.

To do this, we write:

const handlePaste = (e) => {
  const pastedText = e.clipboardData.getData('text/plain')
  console.log(pastedText)
  document.execCommand('insertText', false, pastedText);
  e.preventDefault();
}

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

We get the pasted text with:

e.clipboardData.getData('text/plain')

Then pastedText has what we pasted into the div.

Then we run:

document.execCommand('insertText', false, pastedText);

to insert the text by issuing the insertText command with the pastedText .

The rest of the code is the same.

Conclusion

We can listen to the paste event on an element and get the data from the event object of the paste event handler to get the data pasted into an element.

Categories
JavaScript Answers

How to Get the ID of the Clicked Element in the JavaScript Click Handler?

Sometimes, we want to get the ID of the element that we clicked on in the JavaScript click event handler.

In this article, we’ll look at how to get the ID of the clicked element in the JavaScript click handler.

Set the onclick Property of Each Element to the Same Event Handler Function

One way to let us get the ID of the element when we click on an element is to set the onclick property of each element object to the same click event handler function.

For instance, we can write the following HTML:

<button id="1">Button 1</button>
<button id="2">Button 2</button>
<button id="3">Button 3</button>

Then we can write the following JavaScript code to set the event handler of each element to the same click event handler:

const onClick = function() {
  console.log(this.id, this.innerHTML);
}
document.getElementById('1').onclick = onClick;
document.getElementById('2').onclick = onClick;
document.getElementById('3').onclick = onClick;

The onClick function is the event handler for clicks of each button.

this is the element that we clicked on.

We can get the id property to get the ID of the element that’s clicked on.

And innerHTML has the button’s content.

Then we assign the onClick function as the value of the onclick property to each button element.

Therefore, when we click on the Button 1 button, we get:

'1' 'Button 1'

logged.

When we click on the Button 2 button, we get:

'2' 'Button 2'

And when we click on the Button 3 button, we get:

'3' 'Button 3'

logged.

Getting the Element Clicked on from the Event Object

Another way to get the element we clicked on in the event handler is to get it from the event object which is the first parameter in the event handler function.

For instance, we can write the following HTML:

<button id="1">Button 1</button>
<button id="2">Button 2</button>
<button id="3">Button 3</button>

And the following JavaScript code:

const onClick = (event) => {
  console.log(event.srcElement.id);
}
window.addEventListener('click', onClick);

We call window.addEventListener to attach the click event listener to the html element.

Then we get the element that’s clicked on from the event.srcElement property.

And we can get the ID of that element with the id property.

We can replace event.srcElement with event.target :

const onClick = (event) => {
  console.log(event.target.id);
}
window.addEventListener('click', onClick);

and we get the same result.

We can also check if the element we clicked on is a button with the nodeName property.

For instance, we can write:

const onClick = (event) => {
  if (event.target.nodeName === 'BUTTON') {
    console.log(event.target.id);
  }
}
window.addEventListener('click', onClick);

to add an if statement to check if event.target.nodeName is 'BUTTON' before running the console.log method.

This way, we only run the click handler code if we clicked on a button.

Conclusion

We can get the ID of the element that’s clicked from the click event handler.

We can either get the value from this if we use a regular function.

Or we can get the same value from the event object of the click event handler.