7

Ok here the jsfiddle example

http://jsfiddle.net/HTjCT/1/

As you can see you when you hover it is not firing mouseover event

how can i solve this problem ?

i am using Jquery 1.9

<div id='superdiv'>Click Me</div>


$(function () {
    $('#superdiv').on('click', function (event) {
        $('body').append('<div id="super">another');
    });
    $('#super').on('mouseover', function (event) {
        alert('not working');
    });
});

javascript

Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342

3 Answers3

14

You have to use "delegate", like this (to supply "live") $('body').on('mouseover', '#super', function (event) {

Atep
  • 466
  • 13
  • 20
  • 9
    Whilst this is correct, please don't start attaching all your event handlers to the body. Event delegating works by capturing *every* event that bubbles up and then inspecting the source element to see if it matches the element of interest (`#super` here). So every time you mouseover **anything** on the page you are incurring a hit to check whether that element matches. Put your delegates as local as possible to the source, and you will get better performance, rather than sticking to the body every time – WickyNilliams Jan 18 '13 at 14:37
  • This is absolute true, it was just for this example to show delegate. – Atep Jan 18 '13 at 14:39
0

You can also wrap the mouse over event in a function, and call it whenever you add new elements that you want to be affected. That way the issue WickyNilliams pointed out won't affect you.

$(function () { 
    $('#superdiv').on('click', function (event) { 
        $('body').append('<div id="super">another');
        mouse();
    }); 
    function mouse () {
        $('#super').on('mouseover', function (event) { 
            alert('not working'); 
        }); 
    });
    mouse();
}
-2

The div you want to create onclick, is not closed with the '< / div >' tag.

What if you try the following code:

$(function () {
    $('#superdiv').on('click', function (event) {
        $('body').append(
            $('<div/>',{ 'id' : 'super', 'text' : 'tetet'}).mouseover(function(event) { 
                    alert('test'); 
            })
        );
    });
});
Benz
  • 2,317
  • 12
  • 19