Rich-text Reply

Launch an alert when click on a elment is not working

miguelm 01-26-16
Accepted Solution

Launch an alert when click on a elment is not working

Hi,

 

In the following page www.nh-hotels.com when the user types in the search box, a suggestions list is displayed. I want to create an alert when the user clicks on an element of the suggestions list, but is not working. Any idea why?

 

// Create alert when user clicks on the search box (this is working)
$( "#inputSearch" ).on( "click", function() {
alert("click on #inputSearch");
});

 

 

// Create an alert when user clicks on a suggested element  (this is not working)
$( ".maporamaElement" ).on( "click", function() {
alert("click on .maporamaElement");
});

 

Thank you, best regards.

 

maporamaElement.PNG
Level 2

JDahlinANF 01-26-16
 

Re: Launch an alert when click on a elment is not working

[ Edited ]

@miguelm - for .on to work, the element you are binding to needs to exist at the time the code runs.

 

In this example, you are binding to .maporamaElement which unfortunately does not exist until an autosuggest appears.

 

To fix this, you need to find any parent of .maporama that exists when the code runs (e.g., "body") and tell it which subset of elements within that element for which the function should be called, like this:

 

$("body").on("click", ".maporamaElement", function() {
  alert("click on .maporamaElement");
});

Note: A performance enthusiast will suggest that you find the first parent that the results appear within.  As it is written above, every click will cause the evaluation to be performed ("Did they click a .maparamaElement?").  Though very minor, if you add up a few hundred of these types of bindings, it would add a few milliseconds of unnecessary browser processing time to every. single. click.  A more efficient solution would be:

$("#results").on("click", ".maporamaElement", function() {
  alert("click on #results .maporamaElement");
});

 

miguelm 01-26-16
 

Re: Launch an alert when click on a elment is not working

Thank you for your answer @nap0leon it works fine. Smiley Happy
Level 2