Diorist
Diorist

Reputation: 31

jQuery clone iterative divs on hover

I have a series of divs that I want to clone and show/hide on hover to a different div. Although I've figured out how to clone one or all with jQuery, I'm quite stuck on how to clone each iteratively.

The HTML, essentially:

<div id="test">
  <div id="source1" class="src">content1</div>
  <div id="source2" class="src">content2</div>
  <div id="source3" class="src">content3</div>      
</div>

<div id="dest"></div>

I'm thinking the answer probably involves an each function; however the following script errors with "second argument to Function.prototype.apply must be an array" for jquery.min.js:

$(".src").hover(function() {
 $(".src").each(function() {
  $(this).clone().appendTo('#dest');
  return false;
  $('#dest').show();        
 }, function() {
  $('#dest').hide();
  $('#dest').html('');
 });
});

This bit does work nicely to clone every (not each) .src div on hover, however:

$('.src').hover(function() {
    $('.src').clone().appendTo('#dest');
    $('#dest').show();
}, function() {
    $('#dest').hide();
    $('#dest').html('');
}); 

So, to recap, I want each .src div to be cloned to the #dest div when I hover over it, then disappear when I mouse out. Then the next .src div should do the same thing on hover, and so on...without a separate script for each sourceN div. Please, oh wise ones, what am I doing wrong?

Upvotes: 1

Views: 1460

Answers (4)

Jacob Lowe
Jacob Lowe

Reputation: 688

When cloning the div dont make a use the class selector '.src' just use this and it should work with only the hovered div

$('.src').hover(function() {
    $(this).clone().appendTo('#dest');
    $('#dest').show();
}, function() {
    $('#dest').hide();
    $('#dest').html('');
}); 

http://jsfiddle.net/tsb2A/

Upvotes: 1

Andrew Cooper
Andrew Cooper

Reputation: 32586

Have you tried this?

$('.src').hover(function() {
    $(this).clone().appendTo('#dest');
    $('#dest').show();
}, function() {
    $('#dest').hide();
    $('#dest').html(''); 
}); 

Upvotes: 0

Jose Adrian
Jose Adrian

Reputation: 1247

$('#test div').bind({
   mouseenter: function(){
       $('#dest').append($(this).clone());
   },
   mouseleave: function(){
       $('#dest #'+$(this).attr('id')).remove()
   }
});

Is it ok?

Upvotes: 0

rkw
rkw

Reputation: 7297

Your assumption is correct, you need to make use of the $(this) notation.

$('.src').hover(function() {
    $(this).clone().appendTo('#dest');
    $('#dest').show();
}, function() {
    $('#dest').hide();
    $('#dest').html('');
});

Upvotes: 2

Related Questions