dojo.attr¶
Status: | Draft |
---|---|
Version: | 1.0 |
Available: | since 1.2 |
A getter and setter for DOM attributes, events and CSS styles
Introduction¶
dojo.attr() gives you a unified api to deal with DOM Node attribute modifications. Attributes such as “style” and “onclick” or other event attributes are not real attributes but shortcuts to their respective objects or event handlers. On top of that several browsers deal with attribute setting and getting in different ways
1 | node.setAttribute("style", "border:1px solid #ff0033;");
|
for instance won't work in IE.
In Dojo you can do the same thing working in all browsers using following method
1 | dojo.attr(node, "style", {border:"1px solid #ff0033"});
|
Examples¶
Setting different node attributes¶
The following example will set several attributes such as the "tabindex" and "name"
<script type="text/javascript"> function setAttributes(){ dojo.attr('testNode', { tabIndex: 1, name: "nameAtt", innerHTML: "New Content" }); } function displayAttributes(){ dojo.attr("console", "innerHTML", "tabindex: "+dojo.attr("testNode", "tabindex")+"\n" + "name: "+dojo.attr("testNode", "name")+"\n" + "innerHTML: "+dojo.attr("testNode", "innerHTML")+"\n" ); } </script>
<button dojoType="dijit.form.Button" id="buttonOne" onClick="setAttributes();">Set attributes</button> <button dojoType="dijit.form.Button" id="buttonTwo" onClick="displayAttributes();">Get attributes</button> <div id="testNode">Hi friends :)</div> <div id="console"></div>
Setting events¶
This example will demonstrate how you can set events using dojo.attr(). You shoul still consider using dojo.connect when you are dealing with events since you are getting lots more possibilities and granularitiy with using dojo.connect. In particular you get a handle to later disconnect the event.
<script type="text/javascript"> function setupHandlers(){ dojo.attr("testNodeTwo", "onmouseover", function(evt){ dojo.attr("consoleOne", "innerHTML", "The mouse is over"); }); dojo.attr("testNodeTwo", "onclick", function(evt){ dojo.attr("consoleOne", "innerHTML", "The mouse was clicked"); }); } </script>
<button dojoType="dijit.form.Button" id="buttonThree" onClick="setupHandlers();">Setup handlers</button> <div id="testNodeTwo">Hi, try the events! Click me or hover me.</div> <div id="consoleOne"></div>
Setting styles¶
The following example will set the "style" attribute of the given dom node. dojo.attr() takes a hash as it's argument just like dojo.style
<script type="text/javascript"> function changeStyle(){ dojo.attr("testNodeThree", "style", {padding: "5px", border: "1px solid #ccc", background: "#eee"}); } </script>
<button dojoType="dijit.form.Button" id="buttonFour" onClick="changeStyle();">Change style</button> <div id="testNodeThree">Hi, change my style</div>