tags:

views:

72

answers:

1

On my pages after a postback I am trying to return focus to a previously focused element

$(window).load(function()
    {
        $('.focus').focus();


    });


    $(document).ready(function()
    {
        $('input:not([type=button],[type=submit]), select, textarea').focus(function()
        {
            $(this).addClass('focus');

        });

        $('input:not([type=button],[type=submit]), select, textarea').blur(function()
        {
            $(this).removeClass('focus');

        }); 

    });

My code looks like this and it works even for nested elements but looks a little awkward to me, I am just wondering if there is a better/more optimal way of doing it?

+1  A: 

You can chain the selector and put the focus trigger in the dom ready function. You might even try whitelisting the types of input elements you want to focus on instead of blacklist.

$(document).ready(function(){
    $('.focus').focus();
    $('input[type=text], select, textarea').focus(function() {
        $(this).addClass('focus');
        // To save the focused value to a hidden field
        $('#id-of-Hidden-Field').val($(this).attr('name'));

    }).blur(function() {
        $(this).removeClass('focus');
        // remove the focus hidden field
        $('#id-of-Hidden-Field').val('');
    }); 
});

However, I'm not sure how you are saving which element was focused before the postback in order to output it with the focus class on the new page load. If you are doing that somehow, then this code is fine.

Alex Sexton
Thanks for reply. You right, looks like this is what I need to do - add a hidden field and save it there, unless there is a better way.
Victor
If you like the answer, you should mark it correct. :)
Alex Sexton
I sure will. But if you could show me how to save the focused control using hidden field for example, as it seems the best option, I would appreciate that.
Victor
It wasn't really in your question, but done.
Alex Sexton
Thanks for that
Victor