0

I am using modal from bootstrap

<div aria-hidden="hide" aria-labelledby="myModalLabel" role="dialog" tabindex="-1" id="myModal" class="modal fade" style="display: none;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 id="myModalLabel" class="modal-title"></h4>
            </div>
            <div id="myModalBody" class="modal-body modalScroll"></div>
            <div class="modal-footer">
                <button data-dismiss="modal" class="btn btn-default" type="button">Close</button>
            </div>
        </div>
    </div>
</div>

This is my main modal box and I send some information and show modal when I need to inform user at the moment. But my idea is using this modal to show images and when user choose one I will save as avatar. So I created function like below:

<script>
    $('#avatar').click(function() {
        showMessage();
    });

    $('#eee').on('click', function() {
        alert('333');
    });

    function showMessage(){
        var txto = '<div id="eee">test me test</div>';
        $('#myModalLabel').append('Coose Your avatar');
        $('#myModalBody').append(txto);
        $('#myModal').modal('show'); 
    }
</script>

Now when I go on page and click div id = avatar I will see modal window but when I click: test me I have no result. So is it some way to do this?

Termininja
  • 5,689
  • 12
  • 40
  • 45
  • The answer to this problem is [event delegation](http://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) – Omar Aug 28 '14 at 22:26

1 Answers1

2

try adding:

 $('#eee').on('click', function() {
    alert('333');
 });

inside showMessage() ... your problem is that you have to rebind events to dynamically added elements if they are added after (document).ready or in this case the page rendering...

whenever i do this i just make a big function called rebindEvents() that I can call into to let the page know about my new items... just a warning, its not great for performance if you wind up with a lot of jquery elems you have to deal with, knockout is a much better library for dealing with dynamic html then doing it this way.

also, i'm assuming you are going to present a list of avatars, so you may want to swap eee to a class instead of id...

zach
  • 712
  • 2
  • 9
  • 21
  • You were right with bind: `$("#eee").bind("click", abc); function abc() { alert('eee'); }` in showMessage. But i dont know what will be nest for present avatar list ehh – user3733929 Aug 28 '14 at 22:48
  • like i said, you should really look into http://knockoutjs.com/ ... it is a much better way to deal with dynamic html and all the event propagation/bubbling stuff is all handled for you... if you go with the rebind events method you'll wind up with some serious memory issues depending on the the complexity of whatever you are doing... – zach Aug 28 '14 at 23:31