jdogdvr jdogdvr - 1 year ago 88
jQuery Question

JavaScript color picker uses CSS syntax I'm not familiar with?

I'm using jscolor which is a javascript color picker plugin (link).

The documentation uses javascript inside the css class.

<input class="jscolor {padding:20, borderWidth:3}">

How can I achieve this in javascript? I have not seen this before.

My other question is from the following piece of code that comes from jscolor's documentation. It is for showing and hiding the plugin.

<script src="jscolor.js"></script>

<button onclick="document.getElementById('foo').jscolor.show()">
Show Picker</button>

<button onclick="document.getElementById('foo').jscolor.hide()">
Hide Picker</button>

<p><input id="foo" class="jscolor" value="cc4499">

How does this code call the plugin from just including the class

and how does
call the plugin?

does not make sense to me. Where does
come from.

I tried replicating that code in jQuery and it did not work!


Answer Source

When jscolor is loaded with the src tag, it calls itself with a self executing function that on initiation looks for all input and button tags in the DOM that have the class jscolor and then adds a property called jscolor to them. That jscolor object is what you're calling when you do onclick="document.getElementById('foo').jscolor.show()"

The same logic that adds the jscolor object to the input and button tags also looks at the rest of the class data and parses things like {padding:20, borderWidth:3}. That's how that JavaScript-esq code is working in the CSS class.

All of this information was found from the jscolor github page: https://github.com/EastDesire/jscolor/blob/2.0.4/jscolor.js

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download