Jason Genova
Jason Genova

Reputation: 127

JQuery blur function ( from tutorial)

I am following this tutorial, the instructor is going quite fast and not explaining some parts so I am googling lots of documentation and so far its going pretty good. One thing I cant really understand why is that for my .on('blur',function(){.., I need to include function(){} after the duration of 400ms. Why did I not have to include function(){} when I used the focus function? If so, what the heck is the purpose of that function anyway? The instructor just typed this in and i'm not really sure why. By the way I am making a small search engine and the instructor is going through how to do it.

$(document).ready(function(){

    var searchField = $('#query');
    var icon = $('#search-btn');

    $(searchField).on('focus',function(){

        $(this).animate({

            width:'100%'

        },400);

        $(icon).animate({
            right:'100px'
        }, 400);
    });

    $(searchField).on('blur', function(){
        if(searchField.val() == '')
        {
            $(searchField).animate(
                {
                width:'45%'
                },400,function(){});

            $icon.animate({
                right:'45%'
                },400,function(){});


        }

});

})

Upvotes: 0

Views: 42

Answers (1)

David
David

Reputation: 218828

I assume you mean the empty function block here?:

$(searchField).animate(
    {
        width:'45%'
    },400,function(){});  // <-- in here

That's a callback function. Since the animation is an asynchronous operation (which should take 400 ms in this case), it doesn't block the code to wait for it to complete. So if there's something you want to happen after it completes, it would go in that function block.

For example, consider this:

$(searchField).animate(
    {
        width:'45%'
    },400,function(){
        console.log('first');
    });
console.log('second');

Since the code is asynchronous, 'second' will actually be logged to the console before 'first'. This is because while .animate() "does its thing" asynchronously, the rest of the code continues to execute. The callback is then invoked after that asynchronous operation.

Since the function block is empty, you don't actually need it and can probably just omit it entirely. However, it's possible that the instructor in this tutorial is putting it there as a placeholder for a future step.

Upvotes: 1

Related Questions