0

I am calling a JavaScript function like this:

window[className + 'Click']();

The className var contains some other string, in the end, it calls a function like myClick() or whatEverClick(). Thats alright, but is there a way to make the first part case insensitive?

Examples:
classname = whatever --> call whatEverClick()
classname = whatEver --> call whatEverClick()

Is that possible? Thanks!

user1856596
  • 7,027
  • 10
  • 41
  • 63

2 Answers2

4

You probably shouldn't but you can (excluding the specificities of some languages) :

Step 1 : build a lowercase map of all window properties :

var map = {};
for (var key in window) map[key.toLowerCase()] = window[key];

Step 2 : call your function :

map[className.toLowerCase()+'click'](); 

If you want to call it with window as context (this), use

map[className.toLowerCase()+'click'].call(window); 

Demonstration

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 1
    Notice that this calls the function on the map, not on the global object. Elsewise, this is preferable over @Unspecified's answer, +1! – Bergi Apr 04 '13 at 13:28
  • @Bergi You're right. It's probably not important (we rarely need the global object as context) but as we don't know why OP wants this, it's better said that not. I edited. – Denys Séguret Apr 04 '13 at 13:30
  • I totally missed the point about executing function in context of global object, +1! – Mudassir Ali Apr 04 '13 at 13:47
2

Use this solution if it is absolutely necessary for you to execute in the context of Global object otherwise I prefer Solution 2(inspired by dystroy's answer)

Solution 1

if(window[className+"Click"]){
    window[className+'Click']();
}else{
    for(var f in window){
        if(window.hasOwnProperty(f) && typeof window[f]=='function'){
            if(f.toLowerCase() === className.toLowerCase()+'click'){
                window[f]();
            }
        }
    }
}

Solution 2

//Create an Object and store all the references
var functions_hash = {}

for(var f in window){
    if(window.hasOwnProperty(f) && typeof window[f]=='function'){
        functions_hash[f.toLowerCase] = window[f]
    }
}

//execute using the hash later on
functions_hash[className.toLowerCase()+'click']
Mudassir Ali
  • 7,913
  • 4
  • 32
  • 60
  • 2
    OK, it's possible; but please advise against using this. – Bergi Apr 04 '13 at 13:26
  • @user1856596 by the way why do you want to do this ? If you can specify the use case there may be a better way to solve this, this way you'll have to iterate over huge list of properties or you can store them in an object beforehand(as specified in one of the answers) in order to speed it up – Mudassir Ali Apr 04 '13 at 13:39
  • See the updated answer if you really need to do this which saves your computing time – Mudassir Ali Apr 04 '13 at 13:43