0

I am trying to simulate a click on a element that I appended in.

Example:

var html = "<a data-fancybox data-src="#item52" id="fancy52" href="javascript:;">show</a>";

$("#places").append(html);

appended to:

<div id="places"></div>

Then to simulate a click I do the following:

$("#fancy52").click ();

But this doesn't work. My only guess is because the content was added dynamically.

How can I simulate a click on this dynamic element?

user2423476
  • 2,115
  • 8
  • 28
  • 40
  • 1
    With an anchor element, the jQuery `.click()` will trigger handlers bound to the element but won't trigger the default anchor click navigation behaviour. Try calling the DOM `.click()` method instead: `$("#fancy52")[0].click()`. (Also, the code shown has syntax errors on the first ilne, but I assume your real code doesn't have that problem or the anchor wouldn't be added to your page.) – nnnnnn Nov 05 '17 at 05:26
  • That was it. Thanks! – user2423476 Nov 05 '17 at 05:29
  • Actually, your snippet works fine, you just have to fix syntax error - you have mixed `"` in your string. See this demo - https://codepen.io/anon/pen/vWGMvR?editors=1010 By adding `data-fancybox` attribute, click event is handled using event delegation . – Janis Nov 05 '17 at 09:13

1 Answers1

0

try to use jquery Function live ,

$( "a.offsite" ).live( "click", function() {
alert( "Goodbye!" ); // jQuery 1.3+ });

});

Muhammad Ali
  • 129
  • 7