Wednesday, May 9, 2012

Creating Replicated on Web Web page Using jQuery


Introduction
This post shows how to clone elements of a web page using jQuery; for this we will use the .clone() method.
Sometimes we want to copy (clone) elements of a web page; for example, a navigate menu can be placed on the header and on the footer too and there may be many situations that occur where we need to make a clone. Why write something twice if we have the opportunity to use jQuery.
So, let's create a demonstration page for this article.
<body>
    <h2>History of Visual Studioh2>
    <div class="mainBody">
Visual Studio's history probably begins in <strong class="year">1975strong> with Bill and Paul's decision to create Altair BASIC.  Maybe you could start before that but I think that's as far back as you could go and still say it's about Visual Studio at all รข€“ it's at that time that Microsoft decided it was going to have software development products and not, say, toaster automation.
    div>
    <p>
        Some informations.
    p> 
    <p>
        Some more informations.
    p>
body>
Let's assume; we want to copy the 'mainBody'
and place it after the first . To do this we will use the following jQuery:
$('div.mainBody').clone().insertAfter('p:eq(0)');
In the above jQuery, making the clone of the
that has the class "mainBody" and inserting this new clone after the first , in DOM 0 refers the very first
, 1 refers the second
and so on.
Output in the browser:
image001.png
Take one more assumption; what if we want to apply a different style to the cloned copy??
Now, to do that we need to create a style class.
    <style type="text/css">
        .cloneStyle {
            background#ead3d3;
            fontitalic 1.4em "Times New Roman"Timesserif;
        }
    style>
So, we have a style now; let's add it to the cloned copy.
$('div.mainBody').clone().insertAfter('p:eq(0)').addClass('cloneStyle');
Nothing new here; we just added one more attribute .addClass('cloneStyle') to the existing jQuery above.
Now look at the output in the browser:
image002.png
So, that's all about making a clone in a web page. You can dive deeper into this topic to achieve more functionality.

SPONSORS:

No comments:

Post a Comment