Devin Michaelson Devin Michaelson - 5 months ago 5x
Javascript Question

Binding repeated divs with a bit different contents in the divs

I'm working on repeated divs that there are some changes within them. Let say I have some buttons on my page that open a modal dialog when being clicked. However, the content within the modal is a bit different for each button. I mean 80% of what inside the modal is repeatedly used across those button and the remaining 20% changes according to each specific button.

I'm tired of duplicating the whole div (modal) and making just small changes to fit each button because I currently have 24 buttons on the page and the number is increasing in the near future.

So, I'm asking if there's an excellent way to cope with this issue. Thank you all.

ps. Sorry if I'm not so clear in explaining the problem. Just a newbie here lol.


Point all of the buttons to a template modal, and then when a button is clicked, modify the template modal with the dynamic information. You can store the dynamic information in an array of objects, or you could create a system for storing the dynamic information in the HTML, but hidden.

For example:

var contents = [{
    title: "Header 1",
    body: "Body 1"
    title: "Header 2",
    body: "Body 2"

$("button[id^=modal]").click(function() {
    var content = contents[ - 1]; // id gives index of content in array
    $("#myModal .modal-title").html(content.title);
    $("#myModal .modal-body").html(content.body);
<link href="" rel="stylesheet"/>
<script src=""></script>
<script src=""></script>

<button id="modal1" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal 1</button>

<button id="modal2" type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal 2</button>

<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title"><!--Template Title--></h4>
      <div class="modal-body"><!--Template Body--></div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>