Javascript - Jquery .live()
I have a deeply-nested form where levels of elements get added and removed dynamically by the user (using the Jquery-deep branch in Ryan Bates' Complex Forms Examples). I have attached to each of these elements some Javascript functions and I am having trouble getting them to stay .live()
when new elements are added.
I'm trying to get this to work with James Padolsey's Autoresize:
# This code functions but only for existing elements. How to make it .live()?
<%= javascript_include_tag "autoresize.jquery.min" %>
<script type="text/javascript">
$('#notes, textarea, .optionBox').autoResize({
onResize : function() {
$(this).css({opacity:0.8});
},
// After resize:
animateCallback : function() {
$(this).css({opacity:1});
},
animateDuration : 150,
extraSpace : 0,
limit : 210
});
</script开发者_开发知识库>
I've tried inserting the .live() function a few ways but they haven't worked. How can I get it to function here?
Check out plugin livequery
Example of usage
$('textarea').livequery(function(){
if ($(this).attr("class") != "resized"){
$(this).attr("class","resized");
$(this).autoResize({
// On resize:
onResize : function() {
$(this).css({opacity:0.8});
},
// After resize:
animateCallback : function() {
$(this).css({opacity:1});
},
// Quite slow animation:
animateDuration : 300,
// More extra space:
extraSpace : 40
});
}
});
Have you looked at the more preferred method, delegate
you can use live function in fallowing way
$('#notes, textarea, .optionBox').live('click',autoResize({
onResize : function() {
$(this).css({opacity:0.8});
},
// After resize:
animateCallback : function() {
$(this).css({opacity:1});
},
animateDuration : 150,
extraSpace : 0,
limit : 210 }););
event can be onclick,onfocus...etc.
even you can attach the handler and call autoResize through that handler.
same issue like yours, working with event 'click' but required extra mouse click on textarea, with event 'focus' working excellent but text dissapiar after living textarea(for my case)
$('textarea').live('click', function() {
$(this).autoResize({
// On resize:
onResize : function() {
$(this).css({opacity:0.8});
},
// After resize:
animateCallback : function() {
$(this).css({opacity:1});
},
// Quite slow animation:
animateDuration : 300,
// More extra space:
extraSpace : 10
});
});
my working solution :
$('textarea').live('focus blur', function(event) {
if (event.type == 'focus') {
$(this).autoResize({
// On resize:
onResize : function() {
$(this).css({opacity:0.8});
},
// After resize:
animateCallback : function() {
$(this).css({opacity:1});
},
// Quite slow animation:
animateDuration : 300,
// More extra space:
extraSpace : 10
});
}
else
{
$(this).die();
}
});
better solution for this case: use this plugin link text then code is:
$('textarea').live('focus', function() {
$(this).elastic();
});
精彩评论