I've created code for firing some click events. These events are just like nested with using functions. When I click the button the click event called multiple times.
For Ex. I've one button(b1) which opens a sidebar(already hidden). I've another button(b2) which is in the sidebar. When I open sidebar and click on b2 first time, then it's working fine that is it's calling one time. But when I close sidebar and open again the sidebar by using b1 and click on b2, click event triggered twice. Similarly, it triggers multiple times according to sidebar open using b1. Each time the triggers are increasing on click of b1
Below is my code:
<button class="b1">Show Sidebar</button>
<button class="b3">Hide Sidebar</button>
<div class="sidebar">
<input type="text" class="demo">
<button class="b2">Triggers</button>
</div>
<script>
function getSidebarEvents() {
$('.b2').click(function(){
console.log('Triggering Multiple times');
});
}
$('.b1').click(function() {
//Do something to open sidebar
getSidebarEvents();
});
$('.b3').click(function() {
//Do something to close sidebar
});
</script>
I know my function is calling multiple times on every click of b1 and click b2's event is initializing multiple time. But I can't change this structure with big changes because my code is so big now. I need something small change(s) that will help me to fix this.
You should assign the click event handler outside the function like so. Now if you want to simulate a click from inside that function, just call the click event.
function getSidebarEvents() {
$('.b2').click();
}
$('.b1').click(function() {
//Do something to open sidebar
getSidebarEvents();
});
$('.b2').click(function(){
console.log('Triggering Multiple times');
});
$('.b3').click(function() {
//Do something to close sidebar
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments