Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why colour does not change after change colour in loop

Tags:

html

jquery

css

I have the following html code:

<div class="clm class2"></div>
<div class="clm class3"></div>
<div class="clm class4"></div>
<div class="clm class3"></div>
<div class="clm class4"></div>

And I have the following css code:

.clm{
    width:50px;
    height:50px;
    margin-bottom: 10px;
    border-color: black;
}

.class1{
    background: red;
}

.class2{
    background: green;
}

.class3{
    background: blue;
}

.class4{
    background: black;
}

When I clicked div block with class class2, I need change all div's with class3 to class4

For example:

before: <div class="clm class3"></div>

after click: <div class="clm class4"></div>

I have the following js code (jQuery):

$(".class2").click(function(){
        $(".class3").each(function() {
            $(this).attr('class','clm class4');
        });
    });

This code work fine. The colour is changed. I have the following other js script (jQuery):

$(".class4").click(function(){
        $(this).attr('class','clm class1');
    });

If I clicked to div with class4 before click div with class2 the code work ok, but when I clicked to div with class2 and I try to change colour click in div with class4 it's does not work.

P.S. the html code changed correctly and I see right colour.

like image 697
netwer Avatar asked Dec 03 '25 18:12

netwer


2 Answers

You need to use event delegation for all class names that are added/removed dynamically.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$("body").on('click','.class4',function(){
    $(this).attr('class','clm class1');
});
like image 176
Milind Anantwar Avatar answered Dec 06 '25 09:12

Milind Anantwar


The problem is that when you bind the $('.class4') click handler, the elements to which you're dynamically adding the .class4 classname to do not exist. You need to use event delegation as follows:

$('body').on('click', '.class4', function() {
    $(this).attr('class', 'clm class1');
});

jsFiddle Demo

As a post-script to the above, it's also worth noting that using addClass() and removeClass() is apparently much faster than setting the class attribute using attr().

like image 21
BenM Avatar answered Dec 06 '25 08:12

BenM



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!