Raphael Bergeron Raphael Bergeron - 1 year ago 43
jQuery Question

copy a modal but change the text and images

I have a lot of modal on my site and I don't want to copy paste my code everytime just to change text and images.( all the rest of the modal stays the same).Would be appreciated if someone help me achieve that!

so I have this modaleTemplate i'd like to copy everytime, and then I want to change the following:






<!--- PROJECTS 1 -->
<section class="section-full">
<div class="container-full">

<div class="portfolio logo" data-toggle="modal" data-target="#modalProject-1" id="project-1">
<div class="portfolio-wrapper">
<img src="img/portfolio/logo/5.jpg"/>


<!-------- MODAL 1 -->

<!-- Modal Project Template -->
<div class="modal fade" id="modalProject-1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<!--modal body-->
<div class="modal-body">
<div class="container-fluid">
<div class="row">

<!--modal image-->
<div class="col-sm-6">
<img id="modalImage1"/>
<img id="modalImage2"/>
<img id="modalImage3"/>
<!--modal text-->
<div class="col-sm-6">
<h2 id="modalTitle"></h2>
<p id="modalText"></p>

</div><!--modal body-->

<!-- modal project 1 -->
function setModal(modalImage1, modalImage2, modalImage3, modalTitle, modalText){
$('#modalTitle').text('some title');
$('#modalText').text( 'some text' );

Answer Source

You can use jQuery (or vanilla javascript) to change the values of DOM when opening the modal. Remove the <script> tags that you have placed in the modal give id (or class) to elements that you set the value to on the open-event. To change src of an image in jQuery you can use $('#ID-of-img').attr('src','path-here');. To change the text of a header or paragraph (or whatever) in jQuery you can use $('#ID-of-element').text('place text here');.

In your case I would use something like this.

        <div class="col-sm-6">
            <div class="spacer-sm hidden-sm-up"></div>
            <h2 id="modalTitleDef"></h2>
            <p><span id="modalText1Def"></span><br><br><span id="modalText2Def"></span></p>
            <button type="button" class="btn btn-primary btn-md" data-dismiss="modal">Close Project</button>


<!-- project1 = COPY ALL modalTemplate but CHANGE the images and text-->   

    function setModal(modalImage1Def, modalImage2Def, modalImage3Def, modalTitle, modalText1, modalText2){