jQuery Event How to - Bind click event to every element but the selected element








Question

We would like to know how to bind click event to every element but the selected element.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-2.1.0.js'></script>
<style type='text/css'>
#special {<!-- w w w . j a v  a  2  s. c  o m-->
  position: absolute;
  width: 150px;
  left: 50%;
  margin-left: -75px;
  text-align: center;
  top: 50%;
  background-color: #ff0000;
}

.highlight {
  background-color: green;
}
</style>
<script type='text/javascript'>
$(window).load(function(){
    $('#special').on('click', function(e) {
        e.stopPropagation();
    });
    $(document).on('click', function (e) {
        $(e.target).toggleClass('highlight');
    });
});
</script>
</head>
<body>
  <div id="special">Click anywhere but here!</div>
</body>
</html>

The code above is rendered as follows: