0

I have an input box with class use-keyboard-input. I want to have DOM event fire in all click events except when the input box is clicked

I did:

$('*').click(function(event) {


    if ($(this).hasClass('use-keyboard-input') == false){
        console.log(`pressing outside the box`)

        keyboardHidden = false
        $('.keyboard--hidden').each(()=>{
            keyboardHidden = true          
        })


        if (keyboardHidden == false){     //If keyboard is not hidden
            // if (this !== $(".keyboard")) { 
                Keyboard.close();
                console.log(`Close the keyboard`)
            // }
        }
    }


});

However, even when I click inside the input box with class use-keyboard-input, I get the console message

console.log("pressing outside the box")

2
  • Events bubble up the DOM tree to parent elements. Commented Oct 15, 2019 at 3:51
  • as @Pointy mentioned, events bubble up the DOM hierarchy. So click on the input box also fires click event on all of its ancestor elements. Use event.stopPropagation() to prevent event bubbling up. Commented Oct 15, 2019 at 4:02

1 Answer 1

1

Try with Event.stopPropagation() which will prevent further propagation of the current event in the capturing and bubbling phases.

Demo:

$('*').click(function(event) {

  event.stopPropagation();
  if ($(this).hasClass('use-keyboard-input') == false){
    console.log(`pressing outside the box`)

    keyboardHidden = false
    $('.keyboard--hidden').each(()=>{
      keyboardHidden = true          
    })


    if (keyboardHidden == false){     //If keyboard is not hidden
      console.log(`Close the keyboard`)
    }
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  Container
  <input class="use-keyboard-input"/>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.