Can Yuksel
Can Yuksel

Reputation: 3

Dynamically added list item is not effected by earlier jquery function

I've tried to make a list where I can add an item dynamically.

When you hover to a list item then color turns into yellow, otherwise the color will be red. Adding a list item is no problem. if I add "item 6" (in addition to already existing 5 items) adding goes without any problem, I can even sort it with other items. (using sortable from jquery ui).

The problem is "item 6" doesn't turn into yellow when I hover. It seems the hover function doesn't effect newly added item 6 while it still effects the first 5 items.

you can see how it works at http://jsfiddle.net/9uNV2/ (without sortable)

The code is below:

<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
<script>
$(function() {
    $(".list").sortable()

    $(".item").hover(function(){
        $(this).css("background-color","yellow");
    },function(){
        $(this).css("background-color","orange");
    });

    $(".more").click(function(){
        $(".more").before("<div class=\"add-item\"><form action=\"\"><input class=\"new-    item\" type=\"text\" name=\"text\"><input type=\"submit\" value=\"submit\"></form></div>");
        $('.new-item').focus();
        $("form").submit(function(){
            var new_value = $(".new-item").val();
            event.preventDefault();
            $(".add-item").before("<div class=\"item\">" + new_value + "              </div>").trigger('item');
            $(".add-item").remove();
        });
    }); 
});
</script>

</head>
<body>

<div class="list">
    <div class="item">Item 1</div>
    <div class="item">Item 2</div>
    <div class="item">Item 3</div>
    <div class="item">Item 4</div>
    <div class="item">Item 5</div>
    <div class="more">Add more</div>
</div>

</body>
</html>

How can I make sure that "item 6" also be effected by hover function after it's added as 6th element. So it turns into yellow too when hover over it.

Thanks.

Upvotes: 0

Views: 510

Answers (1)

Antoine
Antoine

Reputation: 2807

hover is not supported anymore, you need to use mouseenter and mouseleave like this:

$(document).on("mouseenter", '.item', function () {
    $(this).css("background-color", "yellow");
}).on("mouseleave", '.item', function () {
    $(this).css("background-color", "orange");
});

And you need to use the delegate syntax, to apply it to the newly append elements.

Example: http://jsfiddle.net/9uNV2/1/

Ref: Does jQuery have a handleout for .delegate('hover')?

Upvotes: 1

Related Questions