Skip to content

Instantly share code, notes, and snippets.

@netsi1964
Last active October 2, 2015 04:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save netsi1964/c49fa2d3e5a75f0091cc to your computer and use it in GitHub Desktop.
Save netsi1964/c49fa2d3e5a75f0091cc 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;
})();
@johan
Copy link

johan commented Oct 2, 2015

Neat idea! For the fun of it, I tried to see if I could turn that into an ES2015 one-liner that doesn't need jQuery, and instead populates an "all" object. Nearly got it. ;-)

all = {};
Array.from(document.querySelectorAll('[class]')).reduce(
  ((a, e) => a.concat(Array.from(e.classList))),
  []
).sort().reduce(
  ((a, b) => {
    var l = a[a.length-1];
    return l == b ? a : a.concat(b);
  }),
  []
).forEach(
  (n) => all['$' + n.replace(/-/g, '_')] = Array.from(document.querySelectorAll('.'+n))
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment