Reputation: 5491
Part of the jQuery plugin I'm writing involves wrapping the input <div>
(the content) into a dynamically created <div>
(the container).
My plugin then needs to add event handlers to the container div without changing the content div.
This is the simplest HTML I can write that describes my problem. If you display this and click on the container, the event does 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 that if the lines marked (A) and (B) are switched around the code works as expected. I cannot do this in my plugin because my plugin is somewhat more complicated.
Upvotes: 0
Views: 246
Reputation: 485
You could easily manage with
<!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=" unique_container container">');
$('#content').wrap(container); // (A)
// container.click(function(e){alert('clicked');}); // (B)
});
</script>
</head>
<body>
<div id="content">the content</div>
<script>
$("body").delegate(".unique_container", "click", function() {
alert('now it is clicked.');
});
</script>
</body>
</html>
Please like the page if your problem is resolved.
http://justprogrammer.com/2013/06/25/jquery-basic-concepts/
Please add your uniqe container class here.
Upvotes: 0
Reputation: 570
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 a wrapper element, it is not the same object.
From manual:
The .wrap() function can take any string or object that could be passed to the $() factory function to specify a DOM structure. This structure may be nested several levels deep, but should contain only one inmost element. A copy of this structure will be wrapped around each of the elements in the set of matched elements. This method returns the original set of elements for chaining purposes.
Upvotes: 1