Track onBlur event for parent div only

I am trying to prepare a custom dropdown control for my application. The requirement is here.

Main stream: If I click on the text field, a div will open, and the user needs to select an element from the div. the selected item must be filled in the text box.

Alternative stream: if the user clicks on a text field and then clicks somewhere on the screen, except for the pop-up div, the pop-up div should close.

I can easily reach the main thread. I cannot use the script code for the alternate stream I mentioned. I tried a simple blur event, it did not work.

Please help me solve the problem.

HTML

<input type="text" class="display-none food-textbox" id="txtFood"  value="None"/>
<div class="food-dropdown display-none"> 
    <div class="food-item">Curled Spinach</div>
    <div class="food-item">Veg Mayo</div>
    <div class="food-item">French Toast</div>
    <input type="hidden" id="hdnFoodTargetTxt"/>
</div>

JQuery Code:

$('.food-textbox').on('click', function () {
    var positionOfTb = $(this).offset();
    var widthofTb = $(this).width();
    $('.food-dropdown').removeClass('display-none').offset({ top: positionOfTb.top, left: positionOfTb.left }).css('width', widthofTb + 10);
    $('.food-dropdown').focus();
    $('#hdnFoodTargetTxt').val($(this).attr('id'));
});

$('.food-item').on('click', function () {
    var targetTxt = '#' + $('#hdnFoodTargetTxt').val();
    $(targetTxt).val($(this).html());
    $(targetTxt).next().eq(0).val($(this).html());
    $('.food-dropdown').addClass('display-none');
});
+4
1

stopPropagation , .

:

$('.food-textbox').on('click', function (e) {
    e.stopPropagation();
    var positionOfTb = $(this).offset();
    var widthofTb = $(this).width();
    $('.food-dropdown').removeClass('display-none').offset({ top: positionOfTb.top, left: positionOfTb.left }).css('width', widthofTb + 10);
    $('.food-dropdown').focus();
    $('#hdnFoodTargetTxt').val($(this).attr('id'));
});

$('.food-item').on('click', function (e) {
    e.stopPropagation();
    var targetTxt = '#' + $('#hdnFoodTargetTxt').val();
    $(targetTxt).val($(this).html());
    $(targetTxt).next().eq(0).val($(this).html());
    $('.food-dropdown').addClass('display-none');
});

$(document).on('click', function () {
    $('.food-dropdown').addClass('display-none');
});

: http://jsfiddle.net/IrvinDominin/PKndL/

+3

Source: https://habr.com/ru/post/1542007/


All Articles