CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

JavaScript Onclick Add Class to Another Div: 2 Best Practices

Shawpnendu Bikash Maloroy

June 30, 2024
JavaScript Onclick Add Class to Another Div - 2 Best Practices
Spread the love

JavaScript onclick add class to another div teaches us that in JavaScript, if a user clicks on a div, how we can add a class to another div? In this article, we will explore step-by-step guide on how we can use the onclick event to add a class to another div. You are going to learn the appropriate technique from this discussion.

Table of Contents

  • What is the onclick event?
  • Why use JavaScript onclick to add a class?
  • Basic Syntax
  • Step-by-Step Guide on “JavaScript Onclick Add Class to Another Div”
    • 1. Set Up Your HTML
    • 2. Add JavaScript
    • Output
    • Code Explanation
  • Practical use cases
  • Example with Toggle
    • Output
  • JavaScript onclick add class to another div: Using addEventListener
    • Output
    • Code Explanation
  • Differences Between onclick and addEventListener
  • Tips for Using JavaScript onclick
  • Conclusion

What is the onclick event?

When an element (a div in this case) on the webpage is clicked, an onclick event is generated by default. If you attach an event handler to this onclick event, then you can run an appropriate code block based on the user’s click. If you do not attach an event handler, then the web page will do nothing.

Why use JavaScript onclick to add a class?

We can get many benefits by adding a class to a div using JavaScript. Such as:

  • Styling: You can control or change the appearance of another dependent element dynamically.
  • Visibility: Show or hide other elements.
  • Interactivity: Enhance user engagement by modifying other elements in response to a certain user action.

Basic Syntax

Here is the basic syntax for adding a class to another div using onclick:

document.getElementById("myButton").onclick = function() {
    document.getElementById("targetDiv").classList.add("newClass");
};

In this example,

  • myButton is the ID of the button or element that generates the action.
  • targetDiv is the ID of the div to which we want to add a class.
  • newClass is the class that we want to add.

Step-by-Step Guide on “JavaScript Onclick Add Class to Another Div”

1. Set Up Your HTML

First, create a simple HTML page like below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Onclick Example</title>
    <style>
        div{
            padding: 20px;
            margin: 10px;
        }
        
        .copyDiv1{
            background-color: black;
        }
        .copyDiv2{
            background-color: red;
        }
        .copyDiv3{
            background-color: yellow;
        }
        .copyDiv4{
            background-color: green;
        }
        .copyDiv5{
            background-color: orchid;
        }
    </style>
</head>
<body>
    
    <table>
        <tr>
            <td>
                <div id="div1" style="background-color: black;">Click Me ..</div>
                <div id="div2" style="background-color: red;">Click Me ..</div>
                <div id="div3" style="background-color: yellow">Click Me ..</div>
                <div id="div4" style="background-color: green;">Click Me ..</div>
                <div id="div5" style="background-color: orchid;">Click Me ..</div>
            </td>
            <td>
                <div id="targetDiv">Color Me Plz...</div>            
            </td>
        </tr>
    </table>

</body>
</html>
buymeacoffee

2. Add JavaScript

Next, add JavaScript to handle the onclick event:

<script>

    document.getElementById("div1").onclick = function() {
        document.getElementById("targetDiv").classList.add("copyDiv1");
    };
    document.getElementById("div2").onclick = function() {
        document.getElementById("targetDiv").classList.add("copyDiv2");
    };
    document.getElementById("div3").onclick = function() {
        document.getElementById("targetDiv").classList.add("copyDiv3");
    };
    document.getElementById("div4").onclick = function() {
        document.getElementById("targetDiv").classList.add("copyDiv4");
    };
    document.getElementById("div5").onclick = function() {
        document.getElementById("targetDiv").classList.add("copyDiv5");
    };
    
</script>

Output

JavaScript Onclick Add Class to Another Div – Example 1
buymeacoffee

Code Explanation

In this example, we have five div’s at the left-hand side. Set individual background colors for all five divs. Now, when a user clicks on any of the divs, a new class is assigned to targetDiv.

Practical use cases

  • Toggle Visibility: You can toggle the visibility of a div by adding or removing a class.
  • Change Layout: Modify the layout or style of a div based on user interaction.
  • Interactive Forms: You can direct form inputs by dynamically changing styles.

Example with Toggle

If you want to toggle a class instead of just adding it, here is how you can do it easily:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Onclick Example</title>
    <style>
        div{
            padding: 20px;
            margin: 10px;
            color: blue;
        }
        
        .copyDiv1{
            background-color: black;
        }
    </style>
</head>
<body>
    
    <table>
        <tr>
            <td>
                <div id="div1" style="background-color: black;">Click Me ..</div>
            </td>
            <td>
                <div id="targetDiv">Color Me Plz...</div>            
            </td>
        </tr>
    </table>

</body>
</html>

<script>

    document.getElementById("div1").onclick = function() {
        document.getElementById("targetDiv").classList.toggle("copyDiv1");
    };
    
</script>

Output

JavaScript Onclick Add Class to Another Div – toggle example

The JS code will add the copyDiv1 class into the targetDiv if it’s not present, and remove it if it already added.

JavaScript onclick add class to another div: Using addEventListener

This is the second-most popular approach that we can use to add a class to another div. Using addEventListener provides us a lot more flexibility. While you are trying with onClick event, we are recommending trying this approach as well. And let us know your experience by leaving a comment.

<script>

    document.getElementById("div1").addEventListener("click", function() {
        document.getElementById("targetDiv").classList.add("copyDiv1");
    });
    
</script>

Output

JavaScript Onclick Add Class to Another Div – using addeventlistener

Code Explanation

The HTML code will be the same. Just change the script part. This example does not perform the toggle; rather, just change the targetDiv background color to black. Here we are just trying to replace the onclick event with addEventListener.

Differences Between onclick and addEventListener

If we do not discuss the differences between onclick and addEventListener, then the discussion will be incomplete. Here are the differences for your reference:

FeatureonclickaddEventListener
Multiple HandlersNo, only one handlerYes, multiple handlers allowed
FlexibilityLess flexibleMore flexible
UsageSimple use casesComplex use cases
Table: Differences Between onclick and addEventListener

Tips for Using JavaScript onclick

  • Use Descriptive Class Names: Always use meaningful class names for clarity.
  • Error Handling: Make sure to handle errors, especially if elements might not exist.
  • Performance: Remove unnecessary classes on time. Otherwise, you may get a performance penalty.

Note

Like add, you can also remove classes in the similar way. For example: document.getElementById(“targetDiv”).classList.remove(“copyDiv1”);

Conclusion

Using JavaScript onclick to add a class to another div is an easy and powerful technique. It provides interactivity and allows us to dynamically change styles based on user activities.

By following the examples and tips in this article, you can effectively use this method in your web projects. Discussing “JavaScript onclick add class to another div”, we have explained all the aspects of adding classes to another div. We have also mentioned another approach using addEventListener. Practice this technique regularly. Happy coding!

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

🏋️‍♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨‍✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
«Previous
Next»

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 5 Lesser-Known JavaScript Functions
    5 Lesser-Known JavaScript Functions to Boost Your Coding Efficiency
  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    🎮 Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! 🏆
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! 🐶
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright © 2024 CodersTechZone.com