Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery priority execution

Can anyone help me with this:

$('#n').click(function() {
    $(this).parent().append('<a href="javascript:void()">&nbsp;delete</a>');
    $(this).next().click(function() {
        alert('clicked'); //this not working
    });
    $(this).blur(function() {
        $(this).next().remove();
    });
});

JS Fiddle demo; the problem is that the blur() event is executed before click() event.

like image 226
Nick Avatar asked Dec 15 '10 14:12

Nick


2 Answers

You can use a timeout to postpone the removal for some milliseconds.

example : http://jsfiddle.net/vkun9/7/

$(this).blur(function() {
            var _this = this;
            setTimeout(function(){$(_this).next().remove();},100);
        });

I also moved the blur attaching to be outside of the click handler, as it was adding an additional one each time the element was clicked, and changed the click handler to the focus to avoid multiple remove buttons from repeated clicking on the input, as @dheerosaur noted.

so

$('#n')
    .focus(function() {
        $(this).parent().append('<a href="javascript:void()">&nbsp;delete</a>');
        $(this).next().click(function() {
            alert('clicked'); //this not working
        });
    })
    .blur(function() {
        var _this = this;
        setTimeout(function(){$(_this).next().remove();},100);
    });

What you experience, though, is not a problem. It is the normal behaviour, as the element need to lose focus (fires the blur) before another element can have it.

You should also match the label for attribute with the id of the input element.

like image 155
Gabriele Petrioli Avatar answered Nov 15 '22 06:11

Gabriele Petrioli


Use the outside events plugin and you can do something like this:

$('.input_field input').focus(function() {
    var div = $(this).parent();
    var link = $('<a href="#">delete</a>').click(function(e) {
        e.preventDefault();
        alert('clicked');
    }).appendTo(div);
    $(this).data('delete', link);
}).bind('focusoutside clickoutside', function(e) {
    var link = $(this).data('delete');
    if (link && e.target != link[0]) {
        link.remove();
    }
});

First switch to using the focus event rather than the click event on your input field, some people actually use the keyboard to navigate through form fields ;-).

Then its creating the delete link, adding it to the page and storing a reference to it in on the input field.

Then with the outside event plugin we can bind focusoutside and clickoutside which get triggered when the user tabs or clicks outside the input field. By checking of the target of the event was the delete link or not we can tell if we should remove the link.

Example: http://jsfiddle.net/petersendidit/vkun9/6/

like image 22
PetersenDidIt Avatar answered Nov 15 '22 04:11

PetersenDidIt