Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elsewhere click event?

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

like image 951
Yan Avatar asked Dec 29 '22 03:12

Yan


2 Answers

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.

like image 117
DanneManne Avatar answered Dec 30 '22 21:12

DanneManne


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

like image 32
Spiny Norman Avatar answered Dec 30 '22 22:12

Spiny Norman