I'm trying to put in the contents of one file into a div container on my website. For example, clicking:
<a class="aModal" href="modal1.html"> Click me!</a>
Will load the contents of modal.html and put it into a div named <div id="modalContainer" class="model"><div>"
without having to write multiple lines of code for each page, and to make adding/updating content easier in the future.
Right now I have the following code:
$(document).ready(function () {
$(".aModal").click(function (event) {
//get attributed href
var html= $(this).attr('href');
/// confirmation
console.log(html, "html");
//push html link into modal container
$("#modalContainer").append(html);
//set modal container to active
$("#modalContainer").addClass(" active");
}); // end of function
});
But other than getting the html link/file, I haven't been able to send it into the modal div nor have been able to add the 'active' class. I'm very new to jQuery, so I appreciate the help.
If you are willing to fetch the content of a given url you may use https://api.jquery.com/jQuery.get/
Description: Load data from the server using a HTTP GET request.
jQuery.get( url [, data ] [, success ] [, dataType ] )
But using such strategy, the url must be pointing to an existing resource. So far in the question your example is using href="modal1.html"
hinting that the resource file is laying in the same path as the html content retrieving it. This part wasn't perfectly cleared out yet but let's assume that's the case.
Here I made a very short demo sticking to your original example and just adding the logic to fetch the external content and also preventing the browser to follow the anchor link when it's clicked because we don't want the default behaviour to kick in.
The external resource used, in this case it's an absolute url to a different origin. You may encounter CORS errors depending on your actual scenario that requires to be more specific to be correctly addressed.
$(document).ready(function () {
$(".aModal").click(function (event) {
//otherwise the default behaviour when clicking an anchor would be following the link...
//...and we want to prevent that
event.preventDefault();
var res = $(this).attr('href');
$.get(res, function(data) {
$("#modalContainer")
.append(data)
.addClass("active");
});
});
});
#modalContainer{
overflow: hidden;
height: 5em;
margin: 2em;
padding: 1em;
}
.active{
border: solid 2px red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<a class="aModal" href="https://baconipsum.com/api/?type=all-meat¶s=1&format=text">Click me!</a>
<div id="modalContainer">
</div>
This demo shows the same strategy used before to fetch content but this time to fill something more resembling an actual modal.
The container is styled with position: fixed
and height: fit-content
to be better positioned in the viewport but it won't behave correctly if the viewport is smaller than the modal content. To better address this specific behaviour I suggest to jump to the last demo where the SweetAlert2 is engaged since it deals by itself with those stylings needed to better represent an actual modal including accessibility issues.
The main feature shown here is having a close button in the modal window that when clicked will remove the active
class making it invisible again.
To be fair, the side effect of this approach is the need to fetch the content from a remote url everytime the modal gets engaged. Plus the answer became pretty long becuase tried to cover too many aspects while remaining vague.
As a final note, I suspect that nowadays in terms of semantic html it would be more appropriate to use a <dialog>
to better deal with a modal but so far my answer was more focused on the fetching content side of the matter instead of the modal per se. You may still be interested to read more about it here https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/dialog
$(document).ready(function () {
//adds the click event handler for the #modalContainer .closeBtn
$("#modalContainer .closeBtn").click(function (event) {
//remove the class active from the #modalContainer so it gets display:none again
$("#modalContainer").removeClass("active");
});
//adds the click event handler for any .aModal element
$(".aModal").click(function (event) {
//otherwise the default behaviour when clicking an anchor would be following the link...
//...and we want to prevent that
event.preventDefault();
debugger;
var res = $(this).attr('href');
$.get(res, function(data) {
$("#modalContainer .modalBody").html(data);
$("#modalContainer").addClass("active");
});
});
});
#modalContainer{
display: none;
/*position and size*/
position: fixed;
--margin: 5em;
top: var(--margin);
left: var(--margin);
width: calc(100% - (5em * 2));
height: fit-content; /*dynamic height fitting content*/
/*height: calc(100% - (5em * 2));*/ /*fixed height 100%*/
/* opacity set to 50% */
background-color: rgba(0, 0, 0, 0.5);
}
#modalContainer .closeBtn{
cursor: pointer;
font-size: 2em;
font-weight: bold;
/*positioned to the right relative to the container*/
position: absolute;
top: 10px;
right: 15px;
}
#modalContainer .modalBody{
margin: 3em;
font-size: 1.5em;
}
.active{
display: block !important;
}
.pageContents{
height: 50em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<a class="aModal" href="https://baconipsum.com/api/?type=all-meat¶s=1&format=text">Click me!</a>
<!-- modal container style to be visible only when .active and display:none otherwise -->
<div id="modalContainer">
<span class="closeBtn">×</span>
<div class="modalBody"></div>
</div>
<!-- dummy page content just for the sake of having a scrollbar and demoing the fixed position of the modal -->
<div class="pageContents">
</div>
Or instead of using javascript, you may just embed the external content inside an <iframe>
https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/iframe
$('.aModal').click(function (event) {
const iframeTarget = $(this).data('target');
$(iframeTarget).css('display', 'block');
});
.external-content{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<a class="aModal" data-target="#content1" href="#">Click me!</a>
<iframe
id="content1"
class="external-content"
src="https://baconipsum.com/api/?type=all-meat¶s=1&format=text"
width="100%"
>
</iframe>
But in genearal you may encounter CORS problems if your html is trying to fetch content from foreign origins not allowing such activity.
If your scenario involves an actual modal window, you might be interested in using a library that will deal with the details on its own.
https://sweetalert2.github.io/
This is a demo using SweetAlert2 to achieve something similar as you hinted in your question. The demo has several .aModal
anchors each one opening its own modal:
//sets the click event handler for each element having the aModal class
$('.aModal').on('click', function (event) {
event.preventDefault();
//retrieves the href attribute value of the clicked element
var res = $(this).attr('href');
//retrieves the data-title attribute value of the clicked element
var title = $(this).data('title');
//attempts to fetch the content from the url in res
$.get(res, function (data) {
//when the content is fetched, show the modal using SweetAlert2
Swal.fire({
title: `MODAL TITLE (${title})`,
text: data, //the content of the modal will be set as the content fetched from the external resource
icon: 'info',
confirmButtonText: 'OK',
showCloseButton: true
});
})
//if the fetch failed...
.fail(function () {
console.log('failed to fetch modal content!');
});
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<a class="aModal" data-title="1" href="https://baconipsum.com/api/?type=all-meat¶s=1&format=text">Click me! for modal(1)</a>
<br>
<a class="aModal" data-title="2" href="https://baconipsum.com/api/?type=all-meat¶s=2&format=text">Click me! for modal(2)</a>
<br>
<a class="aModal" data-title="3" href="https://baconipsum.com/api/?type=all-meat¶s=3&format=text">Click me! for modal(3)</a>