开发者

How to detect clicking off of an element

Basically I want user to click on any .editable item, which makes an input appear, copy its styles, and then if they click anywhere else, I want the input to disappear and the changes to sav开发者_如何学Pythone. I'm having difficulty making this work. I've seen a solution using event.stopPropagation, but I don't see how to include it the way I have my code structured:

$(function() {
    var editObj = 0;
    var editing = false;   

    $("html").not(editObj).click(function(){
         if (editing){
                $(editObj).removeAttr("style");
                $("#textEdit").hide();
                alert("save changes");
            }
    });    


    $(".editable").not("video, img, textarea")
        .click(function(event) {

            editObj = this;
            editing = true;

            $("#textEdit")
                .copyCSS(this)
                .offset($(this).offset())
                .css("display", "block")
                .val($(this).text())
                .select();

            $(this).css("color", "transparent");


    });
}

copyCSS function from here

I need to distinguish between clicks on the editable object, and clicks away from it, even if that click is onto a different editable object (in which case it should call 2 events).


Try this:

$('body').click(function(event) {
    var parents = $(event.target).parents().andSelf();
    if (parents.filter(function(i,elem) { return $(elem).is('#textEdit'); }).length == 0) {
        // click was not on #textEdit or any of its childs
    }
});

$(".editable").not("video, img, textarea")
        .click(function(event) {

    // you need to add this, else the event will propagate to the body and close
    e.preventDefault();

http://jsfiddle.net/dDFNM/1/

This works by checking if the clicked element, or any of its parents, is #textEdit.

The event.stopPropagation solution can be implemented this way:

// any click event triggered on #textEdit or any of its childs
// will not propagate to the body

$("#textEdit").click(function(event) {
    event.stopPropagation();
});

// any click event that propagates to the body will close the #textEdit

$('body').click(function(event) {
    if (editing) {
        $("#textEdit").hide();
    }
});

http://jsfiddle.net/dDFNM/2/


The problem is that you are not correctly binding to the editObj. Perhaps it will help if you move the binding to inside your .editable click handler, or even better use live() or delegate().

$("html").not(editObj)... is bound once at document ready time, and at that time editObj is false

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜