Search code examples
jqueryevent-delegation

.on not working with 1.9.1 jquery version


I want to hide appended div from body. I am using .on with jQuery 1.9.1, but it is not working.

<head>
    <style>
        .brd { border:solid 1px #FF0000; background:#CCCCCC}
    </style>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
        function appendHtml (msg) {
            var htm= '<div class="brd">"' + msg + '"  <a href="javascript:void(0)">close</a></div>';
            $('body').append(htm);
        };
        $(function () {
            $('a').on('click', function () {
                $('.brd').remove();
            });
        });
    </script>
</head>
<body>
    <span onmouseover="appendHtml('hiii there')">append html</span>
</body>

Solution

  • You need to put on on elements already present in document. In your case, a was created dynamically. So, on is not working.

    Choose nearest parent of the element, on which you want an event to be triggered.

    In your case body or document

    $(document).on('click','a',function(){
      $('.brd').remove();
    })