I have the following:
<a href="javascript:jQuery('body').css('backgroundColor','red');">Test</a>
When run in Chrome, it functions as expected and turns the page red. However, in Opera I get:
[object Object]
Closer inspection reveals that Opera thinks that javascript:Query('body')... is some kind of URL. What am I doing wrong? Doesn’t Opera recognize javascript: links in the href attribute?
jsFiddle: http://jsfiddle.net/9CZZL/
Edit: seems to be a Firefox problem too…
The issue is that the return value of
jQuery('body').css('backgroundColor','red')is an object, which some browsers interpret as the new content for the web page. To fix this, you can use the JavaScriptvoidoperator to turn it intoundefined, which FF and Opera (and potentially others) will handle as you intended. You will notice that this issue is also described on that page, since it’s the premier use-case of thevoidoperator (other than code golf wherevoid 0is less characters thanundefined).This should give the intended result: http://jsfiddle.net/9CZZL/13/
It should be noted that handling clicks this way is considered bad practice. Instead, using event handlers in JavaScript is recommended. This helps separate the different layers of your web app, which in turn will make debugging in the future easier.