Rohit Sharma
Rohit Sharma

Reputation: 3334

How to check whether target is removed from the element or not in jQuery?

$(".dropdown-toggle").click(function(event) {
  var target = $(event.target);
  if (target.is(this)) {
    $(this).find(".caret").toggleClass("customcaret");
  }
});
<div class="dropdown-toggle">
  <div class="caret"></div>
</div>

This code is working properly when I click on .dropdown-toggle, .caret is being affected (class is being changed on .dropdown-toggle).

But how I can toggle .customcaret class from .caret on clicking outside the .dropdown-toggle.

Upvotes: 1

Views: 74

Answers (2)

Sanchit Gupta
Sanchit Gupta

Reputation: 3234

You have to make changes in your script like :

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown-toggle" style="float:left;">
  <div class="caret">Click Here</div>
</div>

SCRIPT

$(document).ready(function() {
  $(".dropdown-toggle").click(function(event) {
    event.stopPropagation();
    $(this).find(".caret").addClass("customcaret");
  });
  $("body").click(function() {
    if($(".dropdown-toggle").find(".caret").hasClass("customcaret")){
      $(".dropdown-toggle").find(".caret").removeClass("customcaret");
    }
  });
});

Upvotes: 2

Peter-Paul
Peter-Paul

Reputation: 118

You could make a click event on the body that removes the class 'customcaret' from your element.

Upvotes: 1

Related Questions