How bind the scroll event on a Live()?

倾然丶 夕夏残阳落幕 提交于 2019-12-05 09:11:04

The answer is simple. scroll is what prevents the flickering, because it fires at the very first moment of resize. But scroll has no effect with live (because it doesn't bubble), so your newly created textareas will be resized on keyup but it fires later (thus the flickering).

Update: Of course I can even solve your problem. You just need to ask :) [Demo]

$('textarea.autoresize').live('keyup', function() {
    var el = $(this);
    if (!el.data("has-scroll")) {
        el.data("has-scroll", true);
        el.scroll(function(){
           resizeTextArea(el);
        });
    }
    resizeTextArea(el);
});

The point is, it mixes live with bind. The keyup event, which fires on all elements (because of live), adds the unique scroll event conditionally.

Update 2: Oh, and by the way your whole resizing code can be better written as:

// resize text area (fixed version of Pointy's)
function resizeTextArea(elem) {
    elem.height(1); elem.scrollTop(0);
    elem.height(elem[0].scrollHeight - elem[0].clientHeight + elem.height())
}​

Try this (JSFiddle):

$('#Add').click(function(){
    var id = "newtextarea"+Math.floor(Math.random()*1000);
   $('#pane').append($('<textarea class="new" rows="1" cols="40" id="'+id+'"></textarea><br/>'));
    $('textarea:last').focus();
    bindAgain(id);
});

//inital resize
resizeTextArea($('#tst'));

//'live' event
$('textarea.new').bind('keyup scroll', function() {
    resizeTextArea($(this));
});

function bindAgain(id)
{
    $('#'+id).bind('keyup scroll', function() {
    resizeTextArea($(this));
});

}

Basically, it rebinds the event using a dynamically created ID. Not as elegant as karim79's solution, but it works.

I bind it to a custom event that I call whenever something important happens. Like this:

$(body).live('MyCustomEvent', function() {
    $("#MyScrollItem").scroll(function() {
       // Do things here
    }
});

Hope that helps. Short and sweet.

Alex Force

I found a solution to this problem: The problem is where .live and scroll doesnt work.

My solution is to use the bind event.. and Timeout. The timeout will give the DOM time to update eg.

The below code is used to load content when you scroll to the bottom of the page. Take a look at the setTimeout and the bind.

$('.list').bind("scroll",function(){
    $('.list').height()));
    if($('.list').scrollTop() >= ($('.list').height()+ $(window).height())){        
      setTimeout(function(){    //Time out is used as there is a possibility that
        last_function();
      },200);   
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!