dcd0181
dcd0181

Reputation: 1503

Append then remove element with jQuery

Trying to append an element on mouseenter then remove the same element on mouseleave.

$(#foo).mouseenter(function (){
    $(this).append(#bar);
});
$(#foo).mouseleave(function (){
    $(this).remove(#bar);
});

Doesn't work, am I doing something wrong?

Upvotes: 2

Views: 677

Answers (2)

Sampson
Sampson

Reputation: 268344

​$("#foo").on("mouseenter mouseleave", function(e){
    e.type === "mouseenter"
        ? $("#bar").appendTo(this)
        : $("#bar", this).remove() ;
});​

Fiddler: http://jsfiddle.net/AzEnm/1/

Upvotes: 2

aroth
aroth

Reputation: 54806

Not quoting string literals appears to be the most obvious thing. Have you tried:

$("#foo").mouseenter(function (){
    $(this).append("#bar");
});
$("#foo").mouseleave(function (){
    $(this).remove("#bar");
});

jQuery's element-selector function (i.e. $()) expects a string containing a CSS-style selector, like ".someClass" or "#someId" or "div span.label". Passing those things without quotes around them is a syntax error.

Upvotes: 3

Related Questions