0

I know that if I add content dynamically I have to use an event handler for a parent element using on(). But when I use addClass on dynamically added content the class immediately disappears.

Here's the relevant part of HTML (just to make sure I don't missed typos):

<div id="training_management_categories_items">
    <ul style="list-style: none; margin-left:0px; margin-top:0px; padding:0px;" id="training_management_categories_items_ul">
    </ul>
</div>

Here's the code that adds the dynamic elements:

function GetCategories()
{
  var url = './ajax/training_management_data.php';
  $('#training_management_categories_items').html('<ul style="list-style: none; margin-left:0px; margin-top:0px; padding:0px;" id="training_management_categories_items_ul"></ul>');
  $('#training_management_categories_items_ul').append(' \
    <li class="training_management_categories_list"> \
      <a href="" class="training_management_categories_list_a" id="training_management_categories_list_a_all">All</a> \
    </li> \
  ');
  $.ajax({
    url: url,
    type: "POST",
    data: "action=get_categories",
    dataType: 'json',
    success: function (data) {
      $.each(data, function(index, data) {
        $('#training_management_categories_items_ul').append(' \
          <li class="training_management_categories_list"> \
            <a href="" class="training_management_categories_list_a" id="training_management_categories_list_a_'+data.id+'">'+data.name+'</a> \
          </li> \
        ');     
      });
    }
  });
}

$(document).ready(function() {
    GetCategories();
});

But when I click the element the class is added for just like 0.1 seconds (had to switch the background-color for .categories_selected to red to see it) and I don't get why.

$('#training_management_categories_items').on('click', '.training_management_categories_list_a', function () {
    $(this).addClass('categories_selected'); // DOESN'T WORK
    alert( $( this ).text() ); // THIS WORKS
});

So if I click on one of the dynamically created elements it shows the text (for example "All" which is not fetched from php but you get the idea) but doesn't permanently add the class.

And just for me making ABSOLUTE sure I didn't miss anything really really stupid, here's the CSS:

a.training_management_categories_list_a {
    text-decoration:none;
    display:block;
    background-image:url("img/icons/folder.png");
    background-size:16px 16px;
    padding-left:25px;
    background-repeat:no-repeat;
    font-size:9pt;
    background-position:4px 2px;
    height:20px;
    padding-top:2px;
}

a.training_management_categories_list_a:hover {
    background-color:#aaa;
}

a#training_management_categories_list_a_all {
    font-weight:bold;
}

a.categories_selected {
    background-color:#aaa !important;
}

Am I missing something here?

Edit: using jquery-1.10.2.js

5
  • 3
    you have to prevent the default action else the page will get reloaded...so either return false from the event handler or call event.preventDefault() after receiving the event parameter in the handler Commented Aug 21, 2014 at 22:19
  • I think the :hover style gets in the way. Commented Aug 21, 2014 at 22:22
  • @ArunPJohny Oh man... yes you're right of course. I was near to going mad. Thanks! Why didn't you post this as an answer? Commented Aug 21, 2014 at 22:25
  • lol I missed that, the anchor element reloads the page haha Commented Aug 21, 2014 at 22:32
  • just updated my answer for people to know what was the problem. Commented Aug 21, 2014 at 22:35

3 Answers 3

1

Your code is ok, I tried out that in a jsfiddle: http://jsfiddle.net/carloscalla/n42m6gpf/1/

What is happening is that the color you are setting in the a.categories_selected is the same color it was before (in the hover), I changed it to yellow background-color: yellow !important; so you realize it is working. Try clicking the link and you will see how it changes the background color before the alert pops up.

UPDATE: Just for people looking for answers to know. Anchor element reloads the page so styles will be set to the initial ones. You are using ajax so you don't want the page to be reloaded, therefore you should pass an e parameter to your function and use e.preventDefault() on your onClick function to avoid the default behaviour of anchor tag.

Sign up to request clarification or add additional context in comments.

Comments

1

Maybe this works for you, change this line:

$(this).addClass('categories_selected'); // DOESN'T WORK

to this one:

$(this).parent().find('.training_management_categories_list_a').addClass('categories_selected');

I don't know why but I have seen this problem before and solved with this way.

Comments

0

Have you tried inspecting the element to see if the class is present? That usually helps me identify what's going wrong. It might be that another class is overriding the properties from your class...?

1 Comment

Nah, even in your fiddle the problem persists. After clicking the ok button the yellow color gets removed again. The solution is in Arun P Johny's comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.