jquery - Bind event to wrapper element -


part of jquery plugin i'm writing involves wrapping input <div> (the content) dynamically created <div> (the container).

my plugin needs add event handlers container div without changing content div.

this simplest html can write describes problem. if display , click on container, event not fire:

<!doctype html> <html> <head>     <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>        <script type="text/javascript">         $(function(){             var container = $('<div class="container">');                        $('#content').wrap(container);          // (a)             container.click(function(e){alert('clicked');}); // (b)         });     </script>    </head> <body>     <div id="content">the content</div> </body> </html> 

note if lines marked (a) , (b) switched around code works expected. cannot in plugin because plugin more complicated.

try:

var container = $('<div class="container">');            $('#content').wrap(container);           var wrapper = $('#content').parent(); wrapper.click(function(e){alert('clicked');});   

the wrap function makes copy of wrapper element, not same object.

from manual:

the .wrap() function can take string or object passed $() factory function specify dom structure. structure may nested several levels deep, should contain 1 inmost element. a copy of structure wrapped around each of elements in set of matched elements. method returns original set of elements chaining purposes.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -