Reputation:
Can you get an attribute default value so you don't have to repeat it in the following example:
<p title="foo" id="p">Hello, world!</p>
<input type="text" id="i">
<script>
var p = document.getElementById('p'),
i = document.getElementById('i');
i.oninput = function () {
p.title = this.value;
if (this.value == 'bar') {
p.title = 'foo';
}
};
</script>
DEMO
For text field elemets there's a property known as defaultValue
: element.defaultValue
.
Is there something like attribute.defaultValue
? In other words, is there something like p.title = p.title.defaultValue
for the above example?
Upvotes: 5
Views: 185
Reputation: 206078
If you build a nice reusable function like:
function el(id){
var e = document.getElementById(id), a = e.attributes; e.default = {};
for(var k in a)if(typeof a[k]==='object') e.default[a[k].nodeName] = a[k].nodeValue
return e;
}
not only it'll allow you to easily reference a desired element by ID like:
var p = el('p'),
i = el('i');
but also to retrieve at any point any default element attribute like:
p.default.title // "foo"
or in your example:
i.oninput = function () {
p.title = this.value;
if (this.value == 'bar') {
p.title = p.default.title ;
}
};
or shortened like http://jsfiddle.net/jU5Tv/6/ :
i.oninput = function () {
p.title = this.value==="bar" ? p.default.title : this.value;
};
so double pleasure in any way :)
What the function does is: returns a DOM HTMLElement, but at the same time loops any Element's assigned attribute
and stores it inside a self-assigned Object called default
.
Upvotes: 1
Reputation: 471
You could create a data attribute to hold your default title.
<p title="foo" data-default-title="foo" id="p">Hello, world!</p>
<input type="text" id="i">
In the JS:
if (this.value == 'bar') {
p.title = p.dataset.defaultTitle;
}
Upvotes: 0
Reputation: 103358
There is not a default value property for input title attributes.
However, so that you're not repeating yourself you can store this in a variable before updating it:
var p = document.getElementById('p'),
i = document.getElementById('i');
var defaultTitle = p.title;
i.oninput = function () {
p.title = (this.value == 'bar') ? defaultTitle : this.value;
};
Upvotes: 0