Skip to content

Instantly share code, notes, and snippets.

@DougManuel
Forked from netsi1964/defineVarsFromClassName.js
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DougManuel/712156757c1a14db5300 to your computer and use it in GitHub Desktop.
Save DougManuel/712156757c1a14db5300 to your computer and use it in GitHub Desktop.
Define in global scope vars for each used CSS classname

Give me a global var named "$"+class name

I do a lot of pens on CodePen and I tend to use the same pattern building a prototype as a pen.

For instance I use classnames as handles when inputting and outputting data to the test/prototype. For instance I would have an element with the classname source and one with output. So I always create var named $source and one called $output.

Why not write a function to automatically add global vars named "$" + classname?

This gist is that function! It will search for elements with classes on them. Run through them and create global vars named "$"+classname, which it then will assign the value of "$(classname)". So after this function have been executed (defineVarsFromClassNames()) in your global (window) scope you can expect to find vars with jQuery reference to the element.

(function defineVarsFromClassName() {
var needVar = $("[class]"),
definedVars = "";
for (var i = 0; i < needVar.length; i++) {
var $this = $(needVar[i]);
var classes = $this.attr("class").split(" ");
for (var ii = 0; ii < classes.length; ii++) {
var sClassName = $.trim(classes[ii]);
if (sClassName.length > 0) {
var $us = $("." + sClassName);
var sVarName = "$" + sClassName.replace(/\-/g, "_");
if (typeof window[sVarName] === "undefined") {
window[sVarName] = $us;
definedVars += " " + sVarName;
}
}
}
}
return definedVars;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment