php - jQuery click functions in included files not firing -


this question kind of duplicate, answer provided doesn't solve issue. here's related question:

why jquery click doesn't work when included in separate file

i've got php template has overlay div dynamically populating different content, depending upon link clicked. example, have in template:

<a class="icon-search" href="#"></a> <div id="overlay" class="hidden"></div> 

in global.js file, have these functions:

$(document).ready(function(){ $("a.icon-search").click(function () { $("#overlay").load("inc/search.php"); $("#overlay").toggleclass('show hidden'); }); $("#cancel").click(function() { $("#overlay").toggleclass('show hidden'); }); }); 

the cancel button in "inc/search.php"

when click "icon-search", overlay toggles properly, , content of search.php gets loaded, pressing cancel button doesn't work, unless move function search.php file. hate doing this, because makes html messy, , makes reusing things difficult. there way overcome issue, functions work on elements included?

you need use event delegation in order have generated content fire events.

lookup .on() method in jquery documentation (http://api.jquery.com/on/)

try instead:

$(document).ready(function(){     $("a.icon-search").click(function () {        $("#overlay").load("inc/search.php");        $("#overlay").toggleclass('show hidden');     });      $(document).on('click','#cancel',function() {        $("#overlay").toggleclass('show hidden');     }); }); 

using .on() delegate click events on document elements specified selector , work current elements (which in dom when code runs) and future elements (like appended using ajax, when use .load() method).


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -