javascript - How do I refactor modals that operate on different DIVs to be DRY? -


i have 9 small javascript functions on page same thing, open modal content inside div button located.

the difference between them each 1 references different div. i'd refactor code i'm not repeating code modal operation.

here codepen:

javascript:

// finds modal , places ibox content // active inside modal's body  $('[data-target="#enlargeelementmodal"]').on('click', function () {     $('#enlargeelementmodal .modal-body').html($('#ibox-1 .content.active').html()); });  $('[data-target="#enlargestrategymodal"]').on('click', function () {     $('#enlargestrategymodal .modal-body').html($('#ibox-2 .content.active').html()); });  ....and many more of these 

some html:

// important part of enlarge modal <div class="modal modal-wide fade" id="enlargeelementmodal" role="dialog"><!--enlarge screen modal-->       <div class="modal-dialog">              <div class="modal-content">                      <div class="modal-header">                            <button type="button" class="close" data-dismiss="modal">                            <span class="glyphicon glyphicon-remove"></span>                            </button>                            <h4 class="modal-title">element map</h4>                      </div>              <div class="modal-body">                   <p></p>              </div>              <div class="modal-footer">                    <button type="button" class="btn btn-default" data-dismiss="modal">close</button>              </div>         </div>    </div> </div>   // important part of ibox-content <div class="ibox-content mapstyle" id="ibox-1"><!--content inside div body-->                 <div class="active content" id="elementmap"><!--map content-->                 ....content                 </div> </div> 

how refactor modal javascript don't repeat code?

i add data-* attribute onto each button indicate content comes from:

<button type="button" class="btn btn-default btn-xs" data-toggle="modal"      data-target="#enlargestrategymodal" data-content="#ibox-2"> 

and use same code activate every button:

$('[data-target]').on('click',function(){     var target = $(this).data('target');     var content = $(this).data('content');     $(target + ' .modal-body').html($(content + ' .content.active').html());   }); 

live example: http://codepen.io/anon/pen/dojrrz


Comments