DavidF
DavidF

Reputation: 265

Append only once Jquery

Finally, I have my solution but still a little problem.

I have this list

<ul id="tricky_list"> 
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
</ul>​

I want to show only first 3 (three) elements and show remaining two on mouseover with this function

var limit = 3;
var list = $("#tricky_list");
var more = 0;

function tricky_hide(){
    var morec = 0;
    $("li", list).each(function(index) {
        if (index >= limit) {
            $(this).hide();      
            morec = index - limit + 1;
        }
    });

    if (!more) more = morec;

    if (more) {
        list.append('<li class="more">' + more + ' more</li>');
        return true;
    }
    return true;
}


if (tricky_hide()) {
    list.live("mouseover", function() {
        $("li", list).each(function(index) {
            $(this).show();
        });
        $("li.more", list).hide();
    });

    list.live("mouseout", function() {
        tricky_hide();
    });
}

​It works perfectly but I need some clarifications. I have this piece of function

if (more) {
            list.append('<li class="more">' + more + ' more</li>');
            return true;
        }

that appends the <li class="more"> also on mouseout event. If i "mouseover" and "mouseout" on this element infinite times, it write in my html document infinite <li class="more">. How to prevent this? How can I append only once (on page load, i.e.) this element?

Thanks to all!

Fiddle: http://jsfiddle.net/MYM2C/

Upvotes: 1

Views: 3509

Answers (1)

Zathrus Writer
Zathrus Writer

Reputation: 4331

I would say the solution should be as easy as:

li_element = list.find('li.more');
if (more && !li_element.length) {
    list.append('<li class="more">' + more + ' more</li>');
    return true;
} else {
    li_element.show();
}

Upvotes: 3

Related Questions