Reputation: 795
So i am no so good in js... I have a problem after adding div to the dom, cant understand, how to work with it after.
So i have a simple code, which adds div.
$('#add_frame_by_button').click(function(){
$('body').append(crazy_frame);
});
Also have
$("#resizable").draggable().resizable({
resize: function(event, ui) {
//some code
}
});
So how to bind it to work after adding ?
Upvotes: 0
Views: 91
Reputation: 2213
your question it's not enought clear.
I think that it s what you are looking for:
if you want to add a frame, you need to build one , so you have to append this:
<div id='crazy_frame' style='width:200px;height:100px;background-color:red'></div>
I give some size and color in order to be visible for me, of course you can change size and color.
then if you want to give a draggable propety to this 'frame' you only have to call the draggable methode.
<script type="text/javascript">
$(document).ready(function(){
$('#add_frame_by_button').click(function(){
$('body').append("<div id='crazy_frame' style='width:200px;height:100px;background- color:red'></div>");
$('#crazy_frame').draggable();
});
});
</script>
if you do that you will have to face a problem soon. tell me if I m right to follow
Upvotes: 0
Reputation: 12814
I think you are looking for jQuery's .on()
function. Some other answers have mentioned the .live()
function, but this function has been deprecated as of jQuery 1.7.
The .on()
function will let you listen for specific events that bubble up from child elements and respond appropriately. If you apply the .on()
method to the element that will contain the dynamically added <div>
's, you can define a function that will be called anytime a specific event bubbles from a <div>
within that element.
Also, is there a reason you can't simply apply the various .resizable()
and .draggable()
functions in the .click()
handler itself?
Upvotes: 0
Reputation: 3205
You can try traversing to the div after you have appended it and binding the event to it then.
$('body').append(crazy_frame).children('#resizable').draggable()...
What is probably happening now is $("#resizable").draggable()...
is binding the event when you load the page, but you are appending the content after the page loads.
You could also try using jQuery
There was no issue with how the initial click was being attached to the object, so this is not relevant.on()
with a selector to always bind the event, or live()
/delegate()
if you're using jQuery pre-1.7.
Upvotes: 2
Reputation: 3299
Bind as you said is your answer. You will bind the click event to the parent elements and it will watch for any click events coming through. Currently you are only setting the click event on the available elements.
Sample from their site:
$('#foo').bind('click', function() {
alert('User clicked on "foo."');
});
Upvotes: 0