Set click event to an element that was inserted via AJAX after page load

3

I'm developing an instant search system with jQuery, Ajax and PHP. I created a navigation system for the keyboard arrows in the resulting search options. It's running smoothly. But what I want to do is that when the 'enter' keypad is pressed on top of one of these search options, a 'click' on the selected option is triggered. The problem is that these options are loaded after page loading. So I can not make a click of the traditional way with .click() on that element.

I tried to use

$(elementoPai).on('click', 'elementoFilho', function(){

});

But this only assigns a callback to when 'elementoFilho' is clicked. And that's not what I want. What I want is to set! To click! in this 'element' by typing the enter.

Can anyone help me?

Thank you in advance.

    
asked by anonymous 26.04.2016 / 20:38

2 answers

2

click is with the mouse, touch with your finger, keydown with the keyboard ... after all you can not click with the keyboard or type with the mouse.

$(elementoPai).on('click keydown', 'elementoFilho', function(event){
  if (event.type == "click" || event.which == 13) {
    // 13 -> Enter
  }
});
    
26.04.2016 / 20:57
1

You have to bind the element and event listern to the document document DOM. Try this function below, it will work for any DOM element created in the future:

//Vc enqueceu de escolher o selector => elementoFilho é uma classe ou um ID?
//Se for id
$(document).on("click keydown", "#elementoFilho", function(e){
    e.preventDefault();//Se quiser previnir o comportamento default. 
    //ponha seu cdigo aqui
}); 

//Se for class
$(document).on("click keydown", ".elementoFilho", function(e){
    e.preventDefault();//Se quiser previnir o comportamento default. 
    //ponha seu cdigo aqui
});  
    
26.04.2016 / 21:06