jedu
jedu

Reputation: 1331

Jquery .hasClass() method not working on dom click event check

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")

Upvotes: 0

Views: 44

Answers (1)

Mamun
Mamun

Reputation: 68933

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>

Upvotes: 1

Related Questions