0

I want to fire off a click programmatically on an element added via AJAX. How is that possible? This is makes it a bit of a special case because the element is not added to the due to being injected via AJAX.

Is there a proper way to achieve this?

Potney Switters
  • 2,902
  • 4
  • 33
  • 51
  • are you using jQuery?? – Hitmands Apr 08 '16 at 09:39
  • 1
    @Burki — That does the opposite to what is being asked – Quentin Apr 08 '16 at 09:41
  • 1
    Okay, so you research: 1. Finding an element in the DOM, and 2. Programmatically firing a click at it. This ground is **extremely** well-covered, what have you found, and how have you tried to use it? – T.J. Crowder Apr 08 '16 at 09:41
  • Being added by Ajax shouldn't make a difference. If it is in the DOM then it is in the DOM, and you (probably) aren't trying to access it before then. You'll need to provide a proper test case: http://stackoverflow.com/help/mcve – Quentin Apr 08 '16 at 09:42
  • @Burki — The question is asking how to trigger an event, not how to listen for one. – Quentin Apr 08 '16 at 09:42
  • 1
    @Burki: OP wants to *fire* a click, not respond to it. (And there's no indication they're using jQuery.) – T.J. Crowder Apr 08 '16 at 09:42
  • See: http://stackoverflow.com/questions/809057/how-do-i-programmatically-click-on-an-element-in-firefox. It shouldn't matter if the element was added dynamically. – Joels Elf Apr 08 '16 at 09:43
  • Solution was found at http://stackoverflow.com/questions/16500542/jquery-click-on-another-element-and-display-select-options. – Potney Switters Apr 08 '16 at 10:52

2 Answers2

0

Yes, it is possible and you can achieve that in to steps:

  1. Attach the event by event-delegation to the elements added by AJAX:

    $('#wrapper').on('click', '.element', function() { // Add your functionality here });

  2. Trigger the click programmatically:

    $('.element').trigger('click');

The click will work now because you attach it by event-delegation on the first step. Good luck!

Banago
  • 1,350
  • 13
  • 22
0

do this

jquery:

$('#parent').on('click','#element',function(){
 alert('clicked');
});

javascript:

document.getElementById("parent").addEventListener("click", function(e) {
    if(e.target && e.target.id== "element") {
        alert('clicked');
    }
});

Learn more about event delegation

Note #element is the id of your element,you can change #parent with the closest tag that is not added by the ajax

madalinivascu
  • 32,064
  • 4
  • 39
  • 55