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
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With