.on("click", function() not working when link rendered with ajax
ajax, jquery, ruby-on-rails, ruby-on-rails-3
Solution
Attach an event handler to a parent element using .on(), and pass the selector as an argument.
Example:
$(document).on("click", "a[name=modal]", function(e) {...});
which works for dynamically generated elements as well..
Problem
The link below shows a modal and runs an ajax request to render a partial within the modal based on the object id . The link works fine and the modal pops up when the page is fully loaded with an http request, but if I render the link with an ajax request (e.g. a different modal pops up and renders a few of the links) then the js function doesn't run. I tried an alert(); just to check and it doesnt run when its rendered with ajax. I'm using JQuery 1.9.1, previously the js worked with .live('click'), but that has since been removed. I have also tried .click() Any ideas? Thank you! Link ``` <a href="/an-object-id" data-remote=true name="modal"> ``` JS ``` $(document).ready(function() { $("a[name=modal]").on("click", function(e) { $("#mask, #modal").show(); e.preventDefault(); etc... ```