Track onBlur event on Parent Div only

javascript, jquery

Solution

You can stop the click propagation using `stopPropagation` and add a click handler on the document to close the opened dropdown.

Code:

$('.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');
});

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

Problem

I am trying to prepare a custom dropdown control for my application. The requirement goes here. Main Flow: If i click on the textbox, a div opens and user need to select a item from the div. the selected item needs to be filled into the textbox. Alternate Flow : If the user clicks on the textbox and later clicks on somewhere on the screen except the dropdown div, the dropdown div should close. I am able to achieve the main flow easily. I am unable to script code for the alternate flow i have mentioned. I have tried the simple blur event, it didnt work. Please help me solve the issue. 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'); }); ```

Original source