M1X
M1X

Reputation: 5354

jQuery on scroll not working with createElement on JS

I have a function which creates a div via createElement() in JavaScript. The problem is that the scroll event is not fired on this div. The weird thing is that the click event fires but not the scroll event. This worked well when I created the div via $.html() on jQuery.

Also my two other functions that scroll the div on hovering on .direction_left and . direction_right don't work either. Also these worked well when I created the div via $.html(). What is the problem here? Thanks.

this is the scroll function to load data via ajax.

var scroll = true;

$(document).on('scroll', '#infinited', function() {
    alert('scroll');
    var div = $(this);

    if(div[0].scrollWidth - div.scrollLeft() == div.width()) {

        if(scroll == true) {
            $.post('ajax/user/get_infinited.php', {'start': div.children().length}, function(data) {
                if(data == '')
                scroll = false;
            div.append(data);
            });
        }
    }
});

this is the function which creates the infinited div.

create_infinited: function() {
    if(!document.getElementById("i")) {
        var i = document.createElement("div");
            i.id = 'i';
            i.style.position = 'relative';

        var infinited = document.createElement("div");
            infinited.id = 'infinited';

        var direction_left = document.createElement("div");
            direction_left.className = 'direction_left';

        var direction_right = document.createElement("div");
            direction_right.className = 'direction_right';

        i.appendChild(direction_left);
        i.appendChild(infinited);
        i.appendChild(direction_right);

        $('#search_form').after(i);
    }
}

Upvotes: 1

Views: 167

Answers (1)

laszlokiss88
laszlokiss88

Reputation: 4071

It isn't working because the scroll event doesn't bubble up in the DOM (if you check for example the click event, it will work and that proves that the problem is not in your code - or at least not the way you'd expect).

However, in modern browsers you can capture the scroll event on the document level via the addEventListener, like this:

document.addEventListener(
    'scroll', 
    function(event){
        var $elm = $(event.target);
        if( $elm.is('#infinited')){
            // put your code here
        }
    },
    true
);

Or you can move your "data loader logic" to a function (let's call it getInfinited) that can be accessed in create_infinited, and subscribe there:

$('#search_form').after(i);
$('#infinited').on('scroll', getInfinited);

Upvotes: 1

Related Questions