Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.click not registering changed class

I am trying to create a script that will change the class of another element to avoid the script from being activated under the new class, however, it is not registering with the script, the script considers the old class to still be there.

<script>
$(document).ready(function(){
 $(".element1").click(function(){
  $(".element1").addClass("clicked");
  $(".element1").removeClass("element1");
});});
</script>

Current code is above with what i am trying to achieve.

like image 630
Dan Ross Avatar asked Sep 03 '26 20:09

Dan Ross


2 Answers

The element(s) that has class element1 was binded to a click handler on load...

Even if you remove the class from it, it still is binded to the event handler.
As you can see below:

$(document).ready(function(){
    $(".element1").click(function(){
        console.log("click");
        $(".element1").addClass("clicked");
        $(".element1").removeClass("element1");
    });
});
.element1{
  color:blue;
}
.clicked{
  color:red;
} 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element1">element 1</div>

I suggest you to use off() like this:
Thanks to Dashtinejad for mentionning that .unbind() is deprecated as of jQuery 3.0... Works the same.

$(document).ready(function(){
    $(".element1").click(function(){
        console.log("click");
        $(this).off("click").addClass("clicked").removeClass("element1");

    });
});
.element1{
  color:blue;
}
.clicked{
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element1">Element 1</div>

And use chaining...
;)

like image 195
Louys Patrice Bessette Avatar answered Sep 06 '26 10:09

Louys Patrice Bessette


Try this, you can achieve it by using onclick of particular element. Here the on click listener is binding to the ".element1" in the document at the time of clicking.

if you want to execute a click event only one time then you can also use .one()

$(".element1").one("click",function(){ 
    <!-- your code here -->
});

$(document).ready(function() {
  $(document).on("click", ".element1", function() {
    console.log("click");
    $(".element1").addClass("clicked");
    $(".element1").removeClass("element1");
  });
});
.element1 {
  width: 100px;
  height: 100px;
  background-color: green;
}
.clicked {
  width: 100px;
  height: 100px;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="div1" class="element1"></div>
like image 24
vijay Avatar answered Sep 06 '26 09:09

vijay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!