1

I have the following code you can test it on http://jsfiddle.net/XBfMV/29/

html:

<div class="sam">div 1</div>
<div class="sam">div 2</div>
<div class="sam">div 3</div>
<div class="sam">div 4</div>

css:

.expanded{
    border-style:solid;
    border-width:1px;
    border-color:black;
    background-color:yellow;
    min-height:50px;
}

javascript:

$('.sam').on('click',function(){   

    if ( $(this).hasClass('expanded') ){
        $(this).removeClass('expanded');
    } else {
        $(this).addClass('expanded');

    }

});

$(document).ready(function(){
    //Im just test to write some divs after document ready
    var output = '<div class="sam">div 5</div>';
    $(output).insertAfter('.sam:last').fadeIn('slow');
    var output = '<div class="sam">div 6</div>';
    $(output).insertAfter('.sam:last').fadeIn('slow');
});

after running when click on the div1 , div2, div3 and div 4 it added/remove the .expanded class to the div but when clicking on the div5 and div6 which is generated by java and printed to the document it will not add/remove the class from them when I click into them.

any solutions?

Mohammed Shannaq
  • 806
  • 3
  • 8
  • 21

3 Answers3

2

Add selector to the on function.

Write:

$(document).on('click', '.sam', function () {
    if ($(this).hasClass('expanded')) {
        $(this).removeClass('expanded');
    } else {
        $(this).addClass('expanded');
    }
});

Updated fiddle here.

Refer syntax.

codingrose
  • 15,563
  • 11
  • 39
  • 58
2

Use

$(document).on('click','.sam',function(){   

because you are clicking in dynamic way.

Manish Jangir
  • 5,329
  • 4
  • 42
  • 75
2

.on() only binds to elements already in existence, unless you delegate the actions.

Something like this will work:

$('body').on('click', '.sam', function() {
    // your code here
}
elixenide
  • 44,308
  • 16
  • 74
  • 100