DEV Community

Avnish
Avnish

Posted on

javascript show/hide div onclick

Approach 1: Using .show() Method

  • Purpose: Explicitly displays a hidden div.
  • Limitation: You can't use it to hide the element again.
  • Code Overview:
    • display: none is set initially in CSS for the div.
    • The show(divId) function is called to make the div visible.

Code Behavior:

Clicking the button triggers GFG_Fun(), which calls the show() function, making the hidden div visible.


Approach 2: Using .toggle() Method

  • Purpose: Toggles the visibility of a div.
  • Benefit: Can both show and hide the element.
  • Code Overview:
    • display: none is set initially in CSS for the div.
    • The toggler(divId) function is called, which uses the .toggle() method to show or hide the div.

Code Behavior:

Clicking the button alternates between showing and hiding the div, and updates the text below the button.


Best Practices

  1. Consider Native JavaScript for Simplicity: If you don't need jQuery, you can achieve similar functionality with modern JavaScript:
   function toggleDiv(divId) {
       const div = document.getElementById(divId);
       div.style.display = (div.style.display === "none" || div.style.display === "") ? "block" : "none";
   }
Enter fullscreen mode Exit fullscreen mode
  1. Styling:

    • Ensure proper CSS is applied to handle transitions (e.g., fading in/out for better UX).
    • Use descriptive IDs and class names.
  2. Avoid Inline JavaScript:

    • Use event listeners instead of onClick for cleaner HTML:
   document.querySelector('button').addEventListener('click', () => {
       toggleDiv('div');
   });
Enter fullscreen mode Exit fullscreen mode

Both approaches are solid for toggling a div, and choosing between them depends on your preference for explicit control (.show()) or flexibility (.toggle()).

Top comments (0)