Geniusknight
Geniusknight

Reputation: 639

How to repeat a code in html without writing the same code again and again

Well I wish to show a given piece of code multiple times on a given page but I wish to minimize the redundant code being repeated everywhere (simple copy/paste) . Well I heard of people using Javascript or JQuery to store the given piece of code say HTML or CSS and than they use some simple div renders or the <!--data--> tag multiple number of times in wherever place they want the code to appear, which I have no idea how to use that is store a info in the scripts or html and then render it multiple number of places with a single div or comment.

Can anyone illustrate how to do this with an example. A bit more info on such tricks will be very resourceful.

Upvotes: 8

Views: 20767

Answers (4)

MarmiK
MarmiK

Reputation: 5775

Here is simple JavaScript code to repeat text: (which can be modified as per requirement may be to insert innerHTML)

function repeat(n,Txt){
    for(i=0; i<n;i++)
        document.write(Txt+ char(13)); //char(13) to draw new line
}

Just call this function as per requirement, on window.Load or onclick of a button..

Update: Check this fiddle to Enter repeating HTML fiddle

Code for innerHTML:

function repeat(n,Txt){
    for(i=0; i<n;i++){
        document.getElementById("repeater").innerHTML = 
          document.getElementById("repeater").innerHTML + "<br /> "
           + Txt;
    }
}

Upvotes: 2

lindsay
lindsay

Reputation: 972

An example of reusable code could look like the following (JavaScript example).

var application = {
    addition: function (sum1, sum2) {
        return sum1 + sum2;
    },
    multiplication: function (sum1, sum2) {
        return sum1 * sum2;
    }
};

And you could call it as follows

application.addition(5, 10); /* returns 15 */

Or more complexly

application.multiplicaton(application.addition(5, 10), 2) /* returns 30 */

Upvotes: 1

cracker
cracker

Reputation: 4906

Try Like

<!--#include virtual="/menu.shtml" -->

It will support by most of web servers.

More Info.

Upvotes: 0

imbondbaby
imbondbaby

Reputation: 6411

Have a look at server side includes

Include it like this in your page :

<?php include ('content.html'); ?>

Upvotes: 6

Related Questions