Javascript highlight effect without onclick
Is there a way to change the div background color (highlight) without having to call the function in every input onclick?
Here is my Javascript function:
<script type="text/javascript">
function highlight(element) {
element.parentNode.style.backgroundColor = '#FF9900';
}
function removeHighlight(element) {
element.parentNode.style.backgroundColor = '';
}
</script>
And here is the HTML:
<div class="form-item">
<label>Title:</label>
<开发者_如何学C;input class="form-text Title"
type="text"
onblur="removeHighlight(this);"
onfocus="this.value='';highlight(this);"
onselect="this.value='';"
onclick="this.value='';highlight(this);"
value="english"
name="Title">
<input class="form-text translations"
type="text"
onselect="this.value='';"
onclick="this.value='';"
value="translate"
name="title_translate">
</div>
Here I have to call the function in every input onclick or onselect, which sometimes conflicts with other Javascript functions on my page.
You can anonymously bind it to that specific element:
document.getElementById('foo').onclick = function() {
this.parentNode.style.backgroundColor = '#FF9900';
}
But then you will be forced to use an id
(better than writing the same onclick
code 20 times).
If you were to use a JavaScript library like jQuery, this code could be simplified quite a bit:
$('div.form-item input').select(function() {
$(this).parent().css('background-color', '#FF9900');
});
$('div.form-item input').blur(function() {
$(this).parent().css('background-color', 'auto');
});
That would take care of all the <input>
elements within the <div>
. No need for anything in the HTML. It's all done on the JS-side.
精彩评论