views:

51

answers:

2

Hi, i have a div to show when i pressed a button and hide when i pressed anywhere.

jQuery(document).ready(function () {
    $(document).click(function (e) {
        if (e.button == 0) {
            $('#DivToHide').hide();
        }
    });

    //If its own, return
    $('#DivToHide').click(function () {
        return false;
    });
    //If it is the button to triger Display, return
    $('#DisplayDivButton').click(function () {
        return false;
    });
});

This works good, except: DivToHide contains a link button which makes a callback. But when i enable the code above, it does not make callback. Not that everything is in updatepanel. Thanks.

A: 

If you return false it will prevent the default action on an event from executing.

When you click on the link inside the DIV, it registers the click handler on the DIV first, and returns false, stopping the underlying link itself actually receiving the click event.

I think that's the reason why your link won't work, but I'm not sure why you have a handler on #DivToHide anyways, couldn't you just remove this and let the click handler on the document handle hiding the DIV, and the click handler on the DisplayDivButton handle showing the DIV?

EMMERICH
Thanks, i use DisplayDivButton to open div. But because of document click, when i press anywhere inside div, it hides itself which is an unexpected behavior. To handle this i use $('#DivToHide').click(function (){return false}) and this prevents hiding. But how can i free my linkbutton both DivToHideClick and doccumnet click, i dont know.
Karalahana
Fair enough. I've seen a solution posted now so guess it's fixed, I think I misunderstood you slightly.
EMMERICH
A: 

Do not target the container div #DivToHide..

target the actual link inside it

//If its own, return
//this will make all links inside DivToHide to cancel default action..
$('#DivToHide a').click(function () {
    return false;
});

although, in case you have more links inside it, you should better add a class or id to the link and target it directly..

Update after comment

You should use the event.stopPropagation(); on the link to stop the event from bubbling up to the other elements.

$('#DivToHide a').click(function (event) {
        event.stopPropagation();
    });
Gaby
@Karalahana, updated my answer..
Gaby
Yes this completely is what i need. Thank you very much.
Karalahana