views:

46

answers:

1

I'm developing an extension, which listens to click events on elements.

Now I have two questions:

  1. Is there a convenient way to detect whether an element is an input element? Like input, textarea in HTML, and textbox in XUL.
  2. If the user clicked on an input element, how to get the position where the user clicked? For example, there's an <input> element, with its value set to blah, and the user clicked between 'l' and 'a', how can I get the index(in this case it's 2)?
+1  A: 

Every event has some data that gets passed with it in the event param. You can do something like this to figure out what was clicked on:

function clickFun(event){
    if (event.target.nodeName == "INPUT") {
     var type = event.target.getAttribute('type').toLowerCase();
     if (type == 'text') {
      console.log('text input');
     } else if (type == 'checkbox') {
      console.log('checkbox');
     }
    } else if (event.target.nodeName == "TEXTAREA") {
     console.log('text area');
    }
}
thing.onclick = clickFun;

You can do this with jQuery which gives you some easy functions to check out information about elements. Up to you if you want to try out a javascript framework.

$(':input').click(function(event){
    var $this = $(this);
    if ($this.is(':text')) {
     console.log('text input');
    } else if ($this.is(':checkbox')) {
     console.log('checkbox');
    } else if ($this.is(':textarea')) {
     console.log('textarea');
    }
});

To get the position of the cursor when they click in a text box or area try checking out this article:

http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/

PetersenDidIt