Reputation: 51
When I click on .letitre, I want to simulate a click in the child element .mybutton
HTML :
<div class="letitre">
<div class="mybutton">Button</div>
</div>
<div class="letitre">
<div class="mybutton">Button</div>
</div>
JS:
This function is working (the click is well simulated) BUT it will always click on the first .mybutton and not in the child .mybutton where .letitre is the parent.
$(function(){
$("body").on("click", ".letitre",function(){
$(".mybutton").click();
});
});
Si I tried this but it's not working (no click at all)
$(function(){
$("body").on("click", ".letitre",function(){
var button = $(this).find(".mybutton");
$(button).click();
});
});
Upvotes: 0
Views: 47
Reputation: 56803
Just another question that is just as easy, if not easier, to solve using no jQuery:
document.addEventListener('click', ({target}) => {
if (target.matches('.letitre')) {
target.childNodes[1].click();
console.log("clicked child:");
}
// just so you see .mybutton gets clicked
if (target.matches('.mybutton')) {
console.log(".mybutton received the click!");
}
})
.mybutton { color: #a00; }
<div class="letitre">Outside
<div class="mybutton">Button</div>
</div>
<div class="letitre">Outside
<div class="mybutton">Button</div>
</div>
Upvotes: 1
Reputation: 178384
You need to find the button and click it, and you need to delegate both if you delegate one
Also it is imperative to stop the propagation or you will loop
$(function(){
$(document).on("click",".letitre", function(){
$(this).find(".mybutton").click();
});
$(document).on("click",".mybutton", function(e){
e.stopPropagation(); // make sure the click stops here
console.log($(this).text())
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="letitre">
<div class="mybutton">Button</div>
</div>
<div class="letitre">
<div class="mybutton">Button2</div>
</div>
Upvotes: 1