Search code examples
jqueryfunctionchildren

Method .children()length behave differently inside and outside of a function


This is my code in jQuery. I have a button (class = "trail"), and a grid of divs with the class="cell". If the current cell has no inner divs, I append one to it. Else, I fadeIn the one it has.

Everything works perfectly. But when I try to put this code in a separate function, variable divnum for some reason gives me a result of 2 (on a cell that I enter for the first time, so it should be 0, not 2).

if the code is outside the function divnum can only be equal to 0 or 1.

Can anyone explain to me where does this divnum=2 comes from when I put my code inside of a var MyFunction = function(){};

"Alert" I used just for debugging.

$('#trail').on('click', function(){ //when i press this button
    $('.cell').mouseenter(function(){
        divnum = $(this).children().length; //check if the div i enter has inner divs in it
        if (divnum == 0) {
            alert('divnum')
            $(this).append('<div class="fade"></div>');} //if not - add a div
        else {
            //alert(divnum)
            $(this).children().fadeIn(10); //if it has children, fade them in
        }
        $('.fade').width(CellSize).height(CellSize); //giving a size to the div that was appended
        $('.fade').mouseleave(function(){
            $(this).fadeOut(1000); //fade out the appended div
        });

    });
});

Solution

  • Your problem is the reference to this in Javascript. Inside the jQuery event, it will be set to the correct DOM element. Check if this works:

    function process( reference ) {
        divnum = $(reference).children().length; //check if the div i enter has inner divs in it
        if (divnum == 0) {
            alert('divnum')
            $(reference).append('<div class="fade"></div>');} //if not - add a div
        else {
            //alert(divnum)
            $(reference).children().fadeIn(10); //if it has children, fade them in
        }
        $('.fade').width(CellSize).height(CellSize); //giving a size to the div that was appended
        $('.fade').mouseleave(function(){
            $(reference).fadeOut(1000); //fade out the appended div
        });
    }
    $('#trail').on('click', function(){ //when i press this button
        $('.cell').mouseenter(function(){
            process( this );
        });
    });