I have an onClick event to change style. How to change style back when a user clicks elsewhere of an item?
Both prototype and scriptaculous libraries included.. many of the below answers doesn't work with them... Also ID of an element is UNDEFINED so it can't be used for reference in javascript.
Thanks, Yan
I have not tested this in all browsers, but if you don't want to introduce any new js framework, this solution only use CSS:
<ul>
<li tabindex="1">First</li>
<li tabindex="2">Second</li>
</ul>
The property tabIndex makes the li element focusable. And the css:
li { color: #F00; }
li:focus { color: #0F0 }
This is of course very basic styling, probably want to put it in classes or whatever.
Great question! You can use "event bubbling", which means that instead of the onclick event on your element, you define an event handler on a higher object (say, document
or a table
), and there you say something like:
if (event.target === myElement) {
changeStyle();
} else {
changeStyleBack();
}
More here (and elsewhere): http://www.southsearepublic.org/tag/Javascript%20Event%20Bubbling/read
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With