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";
        }
      };
 });
1

1 Answer 1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.