Becky Becky - 2 months ago 9
jQuery Question

Triggering div click

I'm dynamically appedning a div.

$('#parent').append('<div id="sub"></div>');


How can I trigger a click event on this DIV when an image (
#go
) is clicked?

html

<img id="go" src="img.png" />
<div id="parent"></div>


js

$('#go').on('click',function(){
//console.log("test1");
$("#sub").click();
});

Answer

This should work... Added a handler to verify...

$('#parent').append('<div id="sub"></div>')
$('#go').on('click', function() {
  $("#sub").click();
})

$('body').on('click', '#sub', function(e) {
  console.log('sub clicked')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="go" src="https://i.stack.imgur.com/wPE0C.jpg?s=48&g=1" />
<div id="parent"></div>

Note: Clicking #sub also triggers the event