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?
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>
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
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
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
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:
Feature | onclick | addEventListener |
---|---|---|
Multiple Handlers | No, only one handler | Yes, multiple handlers allowed |
Flexibility | Less flexible | More flexible |
Usage | Simple use cases | Complex use cases |
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.
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!
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply