views:

509

answers:

4

Here is my problem, I'm designing a website that allows you to select a certain item from a list by clicking on it using the onClick attribute. I would like to be able to deselect the item by clicking anywhere else on the page. I tried doing <body onClick="deselect()"> but then if I click anywhere on the page it deselect my item (even when I first click to select it!).

So is there a way to detect if the user clicked somewhere else on the page then on my list?

Thanks a lot.

Edit : I tried onBlur and handleClick with mixed results. The handleClick method get called twice when I click on the item I wish to select, selecting it and deselecting it immediately.

A: 

look at onBlur

Paul Whelan
I just tried onBlur, and it is not always working, when I try to click on an empty region, it it doesn't seem to loose the focus
Gab Royer
using your deselect method you can check the source of the event if its your element then don't deselect the item. that should work too
Paul Whelan
A: 

http://www.w3schools.com/jsref/jsref_onblur.asp

Blur is when the focus is 'lost' from your element

Michael
+3  A: 

onblur is not going to cut it as this isn't a standard HTML input element.

You want to inspect what this refers to when the onclick event is called. If it refers to an item in your list, then you can select the item in the list. If it refers outside of the list, then deselect all of the items in your list.

The code might look something like:

function handleClick(evt) {
   if (this.getAttribute('isListItem')) {
      // highlight
    } else {
      // remove highlighting
    }
    evt.preventDefault();
}

Using this code depends on having an attribute on the HTML to identify that the element is a list item. You also will want to prevent the event from propagating to any sub elements. I'm not 100% sure if this is necessary, but often because the event propagates to the element which contains your list items.

http://www.w3schools.com/jsref/jsref_onclick.asp

altCognito
Just to be sure I understand what you mean correctly, you suggest putting onClick in the body tag and everywhere else and have them call the handleClick function?
Gab Royer
If I do <body onClick="handleClick(event)"> and <table onClick="handleClick(event)">, the function handleClick get called twice if I click on the table, event if I put the evt.preventDefault
Gab Royer
Yeah, I think you'll just need it onbody, not for the table.
altCognito
A: 

Pseudo-code:

var bodyOnClick = function(){}; // empty, does nothing

listItems.onclick = function(){
    /* Do stuff */
    bodyOnClick = deselect;
};

body.onclick = function() {
    bodyOnClick();
};
J-P
Doesn't work because the listItems.onClick gets called before the body.onClick
Gab Royer