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!

1
  • I answered the how but maybe you could tell us the why ? Commented Apr 4, 2013 at 13:20

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Notice that this calls the function on the map, not on the global object. Elsewise, this is preferable over @Unspecified's answer, +1!
@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.
I totally missed the point about executing function in context of global object, +1!
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']

3 Comments

OK, it's possible; but please advise against using this.
@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
See the updated answer if you really need to do this which saves your computing time

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.