Search code examples
javascriptjquerycss-transitionsblur

How do I clear the blur of an element once clicked, and blur itself again after it being clicked again?


So uh.. I'm trying to make a "unblur"/blur transition to a div element after it getting clicked, using the 2 class names in the following code: unblur and blur, which clear the blur / blur an element, respectively. Please take a look:

$(document).ready(function() {
  var n = false;
  var c = document.querySelector("#n");
  c.addEventListener("click", function() {
    n = !(n);
    $(".content").toggleClass(n ? "unblur" : "blur");
  });
});
.content {
  width: 300px;
  border: solid 1px black;
  padding: 10px;
  filter: blur(8px);
}

.unblur {
  filter: blur(0px);
  transition: filter 1s;
}

.unblur:active {
  filter: blur(0px);
}

.blur {
  filter: blur(0px);
  transition: filter 1s;
}

.blur:active {
  filter: blur(8px);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

<div id="n">
  <div class="content">
    Hello World!</div>
</div>

However, something went wrong when the class "content" attempt to trigger the class "blur" after the "unblur" ones. How do I fix this? Thank you!!


Solution

  • Try something like this...

    Revised Javascript in JQuery

    $(document).ready(function() {
        var c = document.querySelector("#n");
        c.addEventListener("click", function() {
            if($(".content").hasClass("blur")) {
                $(".content").removeClass("blur").addClass("unblur");
            } else {
                $(".content").removeClass("unblur").addClass("blur");
            }
        });
    });
    

    Updated CSS

     .content {
     width: 300px;
     border: solid 1px black;
     padding: 10px;
     filter: blur(8px);
     transition: filter 1s;
     }
    
    .unblur {
      filter: blur(0px);
    }
    
    .blur:active {
      filter: blur(8px);
    }