Current code as follows:
<!DOCTYPE html>
<html>
<body>
<h2>Code to shrink</h2>
<div class="myform1">
<input class="button-primary" type="button" id="btn1" value="ON">
<input class="button-primary" type="button" id="btn2" value="OFF">
</div>
<div class="myform2">
<input class="button-primary" type="button" id="btn3" value="ON">
<input class="button-primary" type="button" id="btn4" value="OFF">
</div>
<script>
const Form1 = document.querySelector('.myform1');
const Form2 = document.querySelector('.myform2');
if(Form1){
Form1.addEventListener('click', (e)=>{
e.preventDefault();
alert(e.target.id);
})
}
if(Form2){
Form2.addEventListener('click', (e)=>{
e.preventDefault();
alert(e.target.id);
})
}
</script>
</body>
</html>
There are 2 divs (myform1 and myform2) hence there are 2 javascript code portions (if(Form1) and if(Form2)) to handle each div as above.
My wish is to maintain the 2 divs as in the html code, yet only 1 javascript code portion to handle both divs event clicked … I imagine that looks like below:
<script>
...
//single handler for both or more divs in the html
if(Form){
Form.addEventListener('click', (e)=>{
e.preventDefault();
alert(e.target.id);
})
}
</script>
How do I achieve the task.
Help highly appreciated, thank you
Clue or code example to achieve shrink my javascript coding
3
Answers
You can use
querySelectorAll
to retrive all HTML components into a list. In your case, you can use the coma operator in the query string to use more more than 1 selector.To handle multiple
<div>
elements with a single JavaScript code portion, you can use a common class for the divs and loop over them to attach the event listener. Here’s an updated example:In this updated code, the
<div>
elements have the common class "myform." We usedocument.querySelectorAll('.myform')
to select all elements with that class, and then we loop over them usingforEach
. For each form, we attach the event listener to handle the click event. The event listener function remains the same as before.By using this approach, you can maintain multiple
<div>
elements in the HTML while having a single JavaScript code portion to handle their click events.Salutations, Shamsul!
This is a tricky one! @Hola’s solution is probably exactly what you want. Personally, I would go one step further. The
addEventListener
method takes two arguments: an event name and a callback. This callback function doesn’t care about what component it’s attached to, so you can separate it out and reuse it, making it clearer exactly which parts of your code are being repurposed. (This has some advantages, too, if you ever want to stop listening for click events). I’m imagining something like so…I totally recommend checking out the Docs on EventTarget.addEventListener, though. There’s a lot, there!
Hope this helps!