Tim Marshall Tim Marshall - 6 months ago 18
Javascript Question

JQuery On Click Outside Of Element

Live Demo On JSFiddle

I know there are extensive questions on here regarding click outside of an element however I cannot resolve my problem.

My menus second tier you can right-click and currently rename the list item. You can do this only by enter;

$("body").on("keydown", "li.Clicked>input", function (e) {
var inputValue = $(this).val();
if(e.keyCode == 13) {
$('ul.inbox-nav > li > ul > li.Clicked a').show();
$("ul.inbox-nav > li > ul > li.Clicked a").text(inputValue);
$("ul.inbox-nav > li > ul > li.Clicked input").remove();
$("ul.inbox-nav > li > ul > li.Clicked").removeClass('Clicked');
}
});


However I am trying to add an outside click event out of the entire menu area so that the above result also occurs or resets, either way, however I cannot set up anything without it seeming to break.

Please Note: Whilst this question has no answer, to see the menu in its fully working form, you must hit the enter key upon choosing to rename otherwise the
.Clicked
class will not be removed.

Answer

Check this out...

You can add a focusout listener for the input-element. To make it work in your usecase, you have to put the listener attachement after your input-element was added to the DOM. The focusout listener fires when you click somewhere else or tab out of the input field.

$('#MailMenuSecondTier li').click(function(e) {
    if ($(this).hasClass('Rename')) {
        $('ul.inbox-nav > li > ul > li.Clicked a').hide();
        $('ul.inbox-nav > li > ul > li.Clicked').append("<input type='text' value='" + $("ul.inbox-nav > li > ul > li.Clicked a").text() + "'>");
        $('ul.inbox-nav > li > ul > li.Clicked > input').select();

        $('ul.inbox-nav > li > ul > li.Clicked > input').focusout(function(){

          var inputValue = $(this).val(); 
          $('ul.inbox-nav > li > ul > li.Clicked a').show();
          $("ul.inbox-nav > li > ul > li.Clicked a").text(inputValue);
          $(this).remove();
          $("ul.inbox-nav > li > ul > li.Clicked").removeClass('Clicked');
        })
    }
});