Search code examples
jqueryhtmlhovercloneeach

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?


Solution

  • 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('');
    });