0
document.onmousedown = function(evt) {
    evt = evt || window.event;
    var target = evt.target || evt.srcElement;
    var tagName = target.nodeName.toLowerCase();
    if (tagName == "input" || tagName == "textarea") {
         // Do your stuff
    } 
    else {
         // Do nothing
    }
};

How can i put upper codes in a function and return tagName as return value?

I tried this, but it seems does not work :

var tagName = (function(){
    document.onmousedown = function(evt) {
        evt = evt || window.event;
        var target = evt.target || evt.srcElement;
        var tagName = target.nodeName.toLowerCase();
        if (tagName == "input" || tagName == "textarea") {
              return tagName;
        } 
        else {
              return "nothing";
        }
      };
 });
TaoPR
  • 5,932
  • 3
  • 25
  • 35
SilverLight
  • 19,668
  • 65
  • 192
  • 300
  • 1
    You can't, really. The `var` expects the value to be available well before the event is ever triggered to provide it. You can instead invoke any logic that depends on `tagName` in place of the `return`. Related: [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Jonathan Lonowski Jul 03 '15 at 07:54

1 Answers1

2

You have to create a function that takes the tagName as parameter and call it in your function, and do anything you want with the tagName in that function.

var handler = function(tagName) {
   // do something with the tagname...
};

document.onmousedown = function(evt) {
    evt = evt || window.event;
    var target = evt.target || evt.srcElement;
    var tagName = target.nodeName.toLowerCase();
    if (tagName == "input" || tagName == "textarea") {
      // Let the handler do somthing for you
      handler(tagName);
    } else {
      // do nothing now.
    }
};

A Demo : jsfiddle

fuyushimoya
  • 9,715
  • 3
  • 27
  • 34