Technology

Using the jQuery clone function

Posted by Pixafy Team

JQuery has many great functions to make a site come alive. One of my favorite functions is .clone() –   it does exactly what its name describes, creating a copy of a single element or set of elements in the DOM and displays it where you want it on the page.  It works great for things like tool tips and more complex hover states.

Here’s an example of how to put it to good use.

Let’s say you have a list style and each “li” has an image and its description. You also have a larger version of the image in the same “li” which is given the property “display:none.” When a user clicks on “view larger image” you want to copy that image and have it appear in a separate div elsewhere, but using positioning have it line up right next to the li as shown in figure 1.

Here would be your product listening html structure <div>:

<ul>
<li>
<div><img src="image.jpg" alt="" /></div>
<div>Product description goes here</div>
<a href="#">view large image</a>
<img src="image.jpg" alt="" style="display:none;" />
</li>
</ul>
</div>

Separate the div and place it in the footer or anywhere you would like to add.

<div class="bubble-box"></div>

Since we have the complete HTML structure let’s move forward and create a jQuery script which will copy the image from the li (in this case, with the) and paste it in the div with the class “bubble-box.”

//Cloning data.
$(".target").mouseenter( function ( ) {
$(".bubble-box").empty()
$(img, this).clone().appendTo(".bubble-box")

// Positioning on same location as real item target is.
// store the height of a target element
t_height =

$(this).height();

// store top position
t_top =

 $(this).offset().top;

// store the height and top position.

t_bottom = t_height + t_top;

// store left position
t_left =

 $(this).offset().left;

//show the bubble-box with the data and right next to the li.

$('.hoverMesg').css({

“position”:

"absolute",

“top”:

 t_top,

“left”:

 t_left,
})
$('.bubble-box).show()
});

//Hide the clone div when mouse leaves.

$('. container').mouseleave(function() {

//This hides it and flushes all the cloned data from DOM

$('.bubble-box').hide().empty();
})

You can customize the values and CSS as per your needs; the sky is the limit! Enjoy.

Questions or comments? Share them below, or tweet us @Pixafy!