Reputation: 7092
Im trying to make a jquery color picker, it should read the background color of whatever element is clicked and return it in a .result div.
Problem: How do I describe "the currently clicked" element?
This is my code:
$("p").click(function () {
var color = $("p").css("background-color");
$(".result").html("That div is <span style='color:" +
color + ";'>" + color + "</span>.");
});
I want this to work for any element which is clicked, not only p. Is there a simple way to do this?
Upvotes: 0
Views: 64
Reputation:
If you are talking about a color picker box which contains a few p
elements representing each color so you dont need to dispatch all click
events on ANY element. You can work with p
s. You can use this
to reference to currently clicked p
:
var color = $(this).css("background-color");
So your code will be:
$("p").click(function () {
var color = $(this).css("background-color");
$(".result").html("That div is <span style='color:" +
color + ";'>" + color + "</span>.");
});
And your HTML may be:
<div class="color-picker">
<p style="background-color: #111;"></p>
<p style="background-color: #333;"></p>
<p style="background-color: #666;"></p>
<p style="background-color: #999;"></p>
</div>
Upvotes: 0
Reputation: 45106
$(document).click(function(ev){
var color = $(ev.target).css("background-color");
});
http://jsfiddle.net/tarabyte/9v2rA/
Upvotes: 1