Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  188] [ 4]  / answers: 1 / hits: 7727  / 11 Years ago, mon, january 13, 2014, 12:00:00

Having html list as ,



<ul id=slider>
<li class=></li>
<li class=></li>
<li class=></li>
<li class=selected></li>
<li class=></li>
<li class=></li>
<li class=></li>
<ul>


I am adding selected class to any of the li element.
Here i have added class=selected to fourth li element.



Want to execute some code when class selected is added to any of the li element.



tried this one , but not working as expected.



<script>
$(function() {
$('#slider').bind('DOMSubtreeModified', function(e) {
alert(Changed);
});
});
</script>

More From » jquery

 Answers
12

The best way to handle this is just to call your function when you add the class, since it's your code adding it.



There are two common ways to do that:




  1. You might do that with a direct call:



    li.addClass(selected);
    doSomethingBecauseItChanged(li);

  2. Or you can do it by raising your own event on the li element that other code can listen to, which more thoroughly decouples the code adding the class from the code responding to the change.



    Here's the code listening for the event:



    $(#slider).on(added-class, function() {
    alert(Changed);
    });


    And here's the code adding the class and raising the event:



    li.addClass(selected).trigger(added-class);


    Note that added-class is a name I made up, not something that already exists. Use whatever name you like, just make sure not to conflict with existing event types.



    Here's a complete example: Live Copy | Live Source



    <!DOCTYPE html>
    <html>
    <head>
    <script src=http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js></script>
    <meta charset=utf-8 />
    <title>Event Example</title>
    <style>
    li.selected {
    color: green;
    }
    </style>
    </head>
    <body>
    <p>In two seconds, the third item will turn green and you'll see an alert.</p>
    <ul id=slider>
    <li class=>xxxxx</li>
    <li class=>xxxxx</li>
    <li class=>xxxxx</li>
    <li class=>xxxxx</li>
    <li class=>xxxxx</li>
    <li class=>xxxxx</li>
    <li class=>xxxxx</li>
    </ul>
    <script>
    $(#slider).on(added-class, function() {
    alert(Changed);
    });
    setTimeout(function() {
    $(#slider li).eq(2).addClass(selected).trigger(added-class);
    }, 2000);
    </script>
    </body>
    </html>



Alternately, if you don't need IE support, you can use a mutation observer (support matrix), but frankly you really shouldn't need to use those if you control the code that's adding the class.


[#48761] Saturday, January 11, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
analiseb

Total Points: 252
Total Questions: 96
Total Answers: 106

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
analiseb questions
;