I want to send the background color of an element to a function using javascript for example:
<td style="background-color:#ff0000" onClick="getColor()"></td>
Could anyone please give me a pointer as to what I have to do in the getColor() function?
I want to send the background color of an element to a function using javascript for example:
<td style="background-color:#ff0000" onClick="getColor()"></td>
Could anyone please give me a pointer as to what I have to do in the getColor() function?
Share Improve this question asked May 23, 2012 at 13:09 StuyvensteinStuyvenstein 2,4472 gold badges28 silver badges36 bronze badges 2- 1 possible duplicate of How to get the background color of an element using javascript? – Barry Kaye Commented May 23, 2012 at 13:12
- @BarryKaye This is not a duplicate coz that article applies to a single element, I want to use the same function in the onclick method for multiple elements getting their background colors – Stuyvenstein Commented May 23, 2012 at 13:16
3 Answers
Reset to default 2change this to:
<td style="background-color:#ff0000" onClick="getColor(this)"></td>
And this would be the javasctipt:
getColor(elem){
alert(elem.style.backgroundColor);
}
If jQuery is ok:
<td style="background-color:#ff0000" onClick="getColor(this)"></td>
<script>
function getColor(element) {
var bgColor = $(element).css('background-color');
// ... do something with bgColor here...
}
</script>
Modify the call to send the object as param. Like this-
<td style="background-color:#ff0000" onClick="getColor(this)"></td>
And the function would be-
function getColor(obj){
var bgColor = obj.style.backgroundColor;
alert(var);
}