1

I have the following html/javascript stuff

<html>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).mouseup(function(event) {
    $("body").append("Entering function...");
    var element = event.target;
    var color = element.css("background-color");
    $("body").append("That div is <span style='color:" + color + ";'>" + color + "</span>.");
});
</script>

<body>
<div style="background-color:#ff1111;width:100px;height:100px;"></div>
<div style="background-color:#223388;width:100px;height:100px;"></div>
</body>
</html>

When running in firebug with a breakpoint at "var color = element.css("background-color");" it tells me that css is undefined.

What am I doing wrong here?

6 Answers 6

5

The reason why is element is a DOM element and not a jQuery object. To use the css function you need a jQuery object.

var color = $(element).css('background-color');
Sign up to request clarification or add additional context in comments.

Comments

1

You should do

 var color = $(element).css("background-color");

Comments

0

Try var element = $(event.target) instead. The css method is a jQuery method

Comments

0

Try doing:

var element = $(event.target);

Comments

0

To add more in line styling this code will help a lot

var color = $(element).css({'color':'red','background-color':'blue'});

Comments

0

The use of "event" as parameter shrouds the meaning of the global event object.

Use e or any other valid variable name in your callback method.

$(document).mouseup(function(e) {
...

    var color = $(e.target).css("background-color");
    alert("Color is " + color);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.