Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if mouse is clicked other than $(this) element

I want to apply some styling if mouse is clicked inside an element (here .block). If the element is clicked get that element by $(this) and style it. Now after that, when the user clicks other than the $(this) element, I would like to change it back to default styling. How do I detect if mouse is clicked other than $(this) element.

js script so far :

$( document ).ready(function() {

    // when a block is clicked get that specific block
    $('.block').click(function() {
        var block = $(this);
        block.css('background','red');
    });

    //if clicked other than the block do stuff

});

jsfiddle

like image 419
Aamu Avatar asked Aug 29 '15 08:08

Aamu


People also ask

How do I detect a click outside an element?

You can listen for a click event on document and then make sure #menucontainer is not an ancestor or the target of the clicked element by using . closest() . If it is not, then the clicked element is outside of the #menucontainer and you can safely hide it.

How do you check if the mouse is over an element?

You can simply use the CSS :hover pseudo-class selector in combination with the jQuery mousemove() to check whether the mouse is over an element or not in jQuery.

How do you know which element is clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked. Here is the HTML for the examples in this article.

Which method simulates a mouse click on an element?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event.


1 Answers

The better way to do this is using tabindex andd css :focus selector

.container{
  border:1px solid #333;
  width:200px;
  height:200px;
}
.block{
  background-color: #ccc;
  width:50px;
  float:left;
  height:50px;
  margin:20px;
}
.block:focus{
 background-color: red;
 outline:none
}
<div class="container">
  <div class="block" id="block1" tabindex="1">
    </div>
  <div class="block" id="block2" tabindex="1">
    </div>
  <div class="block" id="block3" tabindex="1">
    </div>
  <div class="block" id="block4" tabindex="1">
    </div>
</div>
like image 136
Ankit Agarwal Avatar answered Sep 20 '22 00:09

Ankit Agarwal