2

I am trying to display search results when typing starts in input element. when the user click out side of the input element then the results should dismiss(I am not including the searh results itself yet). I am trying to stop the propagation in keyupto html element. However, the propagation continues upward. and the results are cleared before they are displayed as typed in the input. should I include the keypress too?

$('#inputsearch').keyup(function(event){

    var searchterms=$('#inputsearch').val();
    console.log(searchterms);
    $.ajax({
        type:'POST',
        data:{'searchterms': searchterms},
        url:'displaysearch.php',
        success: function(response){ 
        $("#searchingresults").empty().html(response);
        }
        });
        event.stopPropagation();
    });
    $('html').click(function(){ $('#searchingresults').empty().hide();});
whatever
  • 332
  • 2
  • 16

1 Answers1

1

The event is being carried from parent html to child input, use the following code. It finds the current target being clicked and prevents action. stopPropagation() is mainly used to stop bubbling of event from child to parent and not the other way.

$('html').click(function (event) {
    if(!$(event.target).is('#inputsearch')){
        $('#searchingresults').empty().hide();
    }
});

Demo

In your case, there is a click event defined on $('html'). So this will fire on every element in the DOM; which is happening with your input search element. As soon as you click it for keying up the input value,$('html').click( is being triggered.

Shaunak D
  • 20,588
  • 10
  • 46
  • 79
  • okay.. it worked.. I was thinking about this solution.. but could not figure out why it is bubbling in the first place.. I was not quite sure of the capturing phase.. Thanks buddy – whatever May 16 '15 at 11:11
  • Yes *capturing* is the word. Glad to help. Please accept the answer if this helped you. – Shaunak D May 16 '15 at 11:13
  • i am now confused ... whats actually happening here.. I thought its bubbling... not capturing.. so which way is things going.. please explain.. I am totally stunned.. – whatever May 16 '15 at 11:22
  • 1
    See, bubbling occurs from `child` event propagating to `parent`. In your case the `html` **click** event (`parent`) is getting captured by the `child` which is the `input`. So on click of this `input` the event for hiding search results is being triggered. – Shaunak D May 16 '15 at 11:23
  • Okay... clear now!!!! now how should I turn off the capturing if I want to in jquery? – whatever May 16 '15 at 11:29
  • 1
    It cant be turned off. No current full proof provision. You have to use such hacks. There is a **[`useCapture`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Browser_compatibility)** option available but not sure about jQuery. – Shaunak D May 16 '15 at 11:33