0

This code should create little numbered tags next to each anchor, button, and input element. It then sets up click events on those tags. I have removed the code for the buttons and anchor tags, since it works and is unrelated.

With inputs, however, what should happen is that the cursor should be placed into the input element, achieved using the .focus() method.

But when I run this in the console against a logged-in gmail.com, it does nothing. The commented alert() statement will return [Object HTMLSpanElement], whatever that means. If I uncomment the document.getElementById line to focus on the search bar directly, it works. Why doesn't it work using this?

I'm using gmail just for a testing example, but this behavior is on all pages, the bug is always there. You can include jQuery to test this in the console using this.

var n = 1;
$('a,button,input').each(function(){
                        id = n;
                   //creates numbered tags next to 'a', 'button' and 'input' elements
                        var a = $(this).offset();
                        $('body').append('<span class="numTag" id="' + id + '" style="background:white; border: 1px solid black; font-size: 10pt; position:absolute; z-index:999;">' + id + '</span>');
                        $('#'+id).css({left: a.left - 25, top: a.top});
                        switch( this.tagName)
                        {
                        case 'A':
                            break;
                        case 'BUTTON':
                            break;
                        case 'INPUT':
                            $('#'+id).click(function(){
                                //alert(this);
                                this.focus();
                                //document.getElementById('gbqfq').focus();
                            });
                            break;
                        }
                        n++;
                    }
                });
Community
  • 1
  • 1
temporary_user_name
  • 35,956
  • 47
  • 141
  • 220

1 Answers1

2

You are losing access to this inside the click event. Store a reference to it so that you can access it later.

var self = this;
$('#'+id).click(function(){
    //alert(self);
    self.focus();
    //document.getElementById('gbqfq').focus();
});
Kevin B
  • 94,570
  • 16
  • 163
  • 180