Custom POPUP. There are so many plugins that you can use to call an ajax base form in a popup. In this post, I will create a simple lightweight Jquery based POPUP that you can use in your project. To show any kind of HTML data a simple form (contact us form), alert message or anything as per your need.
This lightweight POPUP creates with the help of JQuery and displays simple form using AJAX. As you know every plugin has many other options that you don’t need at all. So we create our own lightweight script.
Download Plugin.
Click on a file name to download plugin source files lightWeightPopup.js. Add stylesheet into your head tag and script files just before close the body tag </body>. This plugin is JQuery dependent so before plugin js, you need to add JQuery lib.
<link rel="stylesheet" href="lightweightpopup.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="lightWeightPopup.js"></script>
JS CDN
https://cdn.jsdelivr.net/gh/LearnCodeWeb/[email protected]/js/lightWeightPopup.min.js
CSS CDN
https://cdn.jsdelivr.net/gh/LearnCodeWeb/[email protected]/css/lightWeightPopup.min.css
Plugin parameters
These parameters you need to set when you initialized the plugin. The plugin initialization is given below. You can call the plugin by ID or Class.
Options | Description | Data Attribute |
href | An ajax URL | data-href |
width | Popup Model width | data-width |
height | Popup Model height | data-height |
maxWidth | Popup Model max-width | data-maxWidth |
maxHeight | Popup Model max-height | data-maxHeight |
title | Popup Model Title | data-title |
overlay | If set true model close on overlay click. The default value is false. | data-overlay |
modelFixed | If set true model fixed at the top. | data-model-fixed |
Top | The model top position can be set in pixel. | data-top |
You can also use the data attribute to set plugin parameters. Show in the below code. The data-content is a must on the button you must add data-content with the value of ajax or inline. In inline you must pass the .inline class to the structure you want to show in POPUP.
<button type="button" class="btn btn-light mb-3 open-popup" data-href="contact-us.html"
data-content="ajax">Ajax With Callback</button>
<button type="button" id="popup" class="btn btn-primary mb-3" data-overlay="true"
data-href="contact-us.html"><i class="fa fa-fw fa-file-alt"></i> CLICK HERE
AJAX</button>
<button type="button" id="inline" class="btn btn-danger mb-3" data-content="inline"><i
class="fa fa-fw fa-file-alt"></i> CLICK HERE INLINE</button>
<a href="javascript:;" id="ancher" data-href="contact-us.html" class="btn btn-primary mb-3"
data-overlay="true"><i class="fa fa-fw fa-file-alt"></i> Ancher Tag AJAX</a>
<button type="button" id="iframe" data-href="https://www.youtube.com/embed/ZwKhufmMxko"
class="btn btn-warning mb-3" data-content="iframe"><i class="fa fa-fw fa-file-alt"></i> Button Tag
Iframe</button>
<a href="javascript:;"
data-href="https://learncodeweb.com/web-development/how-to-create-a-custom-popup-form-with-php-and-ajax/"
class="btn btn-dark mb-3 iframe" data-content="iframe"><i class="fa fa-fw fa-file-alt"></i> Ancher Tag
Iframe</a>
The plugin initialization code is given below.
$(document).ready(function (e) {
$('.open-popup').lightWeightPopup({
title: 'Popup Title',
width: '500px',
top: '50',
overlay: true,
type: 'ajax',
ajaxHeaders: {
'X-Another-Header': 'some-value',
'Custom-Header': 'another-value'
},
ajaxData: {
'value1': 'some-value-1',
'value2': 'some-value-2',
},
beforeOpen: function () {
alert('The popup is about to open.');
},
openComplete: function () {
alert('The popup has opened.');
},
closeComplete: function () {
alert('The popup has closed.');
}
});
$('#popup').lightWeightPopup({ type: 'ajax', href: 'contact-us.html', overlay: true, width: '90%', maxWidth: '600px', title: 'Ajax Model' });
$('#inline').lightWeightPopup({ type: 'inline', title: 'Inline Model' });
$('#ancher').lightWeightPopup({ type: 'ajax', width: '95%', maxWidth: '320px', title: 'Ajax Model' });
$('#iframe').lightWeightPopup({ type: 'iframe', href: 'https://www.youtube.com/embed/foSaKHdXbss', maxWidth: '600px', height: '400px', title: 'Iframe Model' });
$('.iframe').lightWeightPopup({ type: 'iframe', width: '100%', height: '100%', title: 'Iframe Model' });
});
Create a file with the name of lightWeightPopup.js and paste the below code in it. You can also download this file from here.
/**
** Author: ZAID BIN KHALID
** Website: https://learncodeweb.com
** Version: 0.5
**/
function closeDilog(action, callback) {
if (action === "inline") {
var inlineData = $('#lwpBody').html();
setTimeout(function () {
$('body').find('.lwp-inline').html(inlineData);
$('body').removeClass('lwp-hidden');
}, 100);
}
$('.lwp').remove();
$('.lwp-overlay').remove();
if (callback && typeof callback === "function") {
callback();
}
}
(function ($) {
$.fn.lightWeightPopup = function (options) {
$(this).on("click", function () {
openPopup($(this), options);
});
};
function openPopup(trigger, options) {
var dset = trigger.data();
$("body").find('.lwp').remove();
var settings = {
method: dset.method || 'GET',
href: dset.href || '',
width: dset.width || '',
height: dset.height || '',
maxWidth: dset.maxWidth || '',
maxHeight: dset.maxHeight || '',
title: dset.title || 'Model',
overlay: dset.overlay || false,
modelFixed: dset.modelFixed || false,
ajaxHeaders: dset.headers || {},
ajaxData: dset.data || {},
type: dset.type || '',
};
var windowHeight = window.innerHeight - 160;
// Extend settings with options passed to the plugin
settings = $.extend({}, settings, options);
// Prepare styles for popup
var styles = generatePopupStyles(settings, windowHeight);
// Append popup and overlay
$("body").append(generatePopupMarkup(settings, styles));
// Handle overlay click
if (settings.overlay) {
$('.lwp-overlay').on('click', function () {
closeDilog(settings.type, options.closeComplete);
});
// Prevent closing when clicking inside the `.lwp` content area
$('.lwp').on('click', function (event) {
event.stopPropagation(); // Prevent the click event from reaching the overlay
});
}
// Bind close button event
$('.lwp .close').on('click', function () {
closeDilog(settings.type, options.closeComplete);
});
// Trigger beforeOpen callback
if (options.beforeOpen && typeof options.beforeOpen === 'function') {
options.beforeOpen();
}
// Trigger openComplete after the popup is appended
if (options.openComplete && typeof options.openComplete === 'function') {
setTimeout(options.openComplete, 500); // Ensuring it's called after popup opens
}
// Load content based on type
loadPopupContent(settings);
}
function generatePopupStyles(settings, windowHeight) {
var styles = {
width: settings.width ? 'width:' + settings.width + ';' : '',
height: settings.height ? 'height:' + settings.height + ';' : '',
maxWidth: settings.maxWidth ? 'max-width:' + settings.maxWidth + ';' : '',
maxHeight: settings.maxHeight ? 'max-height:' + settings.maxHeight + ';' : '',
modelFixed: settings.modelFixed === 'fixed' ? 'style="height:' + windowHeight + 'px"' : ''
};
return styles;
}
function generatePopupMarkup(settings, styles) {
return '<div class="lwp-overlay">' +
'<div class="lwp" tabindex="-1" role="dialog" style="' + styles.width + ' ' + styles.height + ' ' + styles.maxWidth + ' ' + styles.maxHeight + '">' +
'<div id="lwp" style="' + styles.width + ' ' + styles.height + ' ' + styles.maxWidth + ' ' + styles.maxHeight + '">' +
'<div id="lwpHead">' +
'<div class="title">' + settings.title + '</div>' +
'<div class="close"><span>×</span></div>' +
'</div>' +
'<div id="lwpBody" role="document" ' + styles.modelFixed + '>' +
'<div class="loading"><img src="https://cdn.jsdelivr.net/gh/LearnCodeWeb/[email protected]/image/loader.gif"><p class="text">Please Wait..!</p></div>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
}
function loadPopupContent(settings) {
var $popupBody = $('#lwpBody');
// Validate the 'type' property
if (!['ajax', 'iframe', 'inline'].includes(settings.type)) {
$popupBody.html("Error: Please define the type parameter. Valid types are 'ajax', 'iframe', or 'inline'.");
settings.type = ''; // Set to empty to avoid further issues
}
if (settings.type === 'ajax') {
$.ajax({
method: settings.method,
url: settings.href,
headers: settings.ajaxHeaders, // Custom headers
data: settings.ajaxData, // Custom headers
success: function (data) {
if (data) {
setTimeout(function () { $popupBody.html(data); }, 1000);
}
},
error: function (xhr, status, error) {
console.error("Error occurred:", status, error);
$popupBody.html("<p>There was an error loading the content. Please try again later.</p>");
}
});
}
if (settings.type === 'iframe') {
try {
var lwpHead = parseInt($('#lwpHead').innerHeight());
var lwp = parseInt($('#lwp').innerHeight());
if (isNaN(lwpHead) || isNaN(lwp)) {
throw new Error("Height calculations failed. Please ensure elements exist and are correctly sized.");
}
var bh = lwp - lwpHead;
setTimeout(function () {
$popupBody.html('<iframe frameborder="0" class="lwpIframe" style="height:' + bh + 'px; width:100%;" src="' + settings.href + '"></iframe>');
}, 1000);
} catch (error) {
console.error("Error in iframe setup:", error.message);
$popupBody.html("<p>Error loading iframe. Please try again later.</p>");
}
}
if (settings.type === 'inline') {
try {
var data = $('body').find('.lwp-inline').html();
if (data) {
setTimeout(function () {
$popupBody.html(data);
}, 1000);
} else {
throw new Error("No inline content found.");
}
$('body').find('.lwp-inline').html('');
} catch (error) {
console.error("Error in inline content setup:", error.message);
$popupBody.html("<p>Error loading inline content. Please try again later.</p>");
}
}
}
})(jQuery);
The CSS code of the plugin is given below.
* {
box-sizing: border-box;
}
.lwp-overlay {
background: rgba(0, 0, 0, 0.9);
padding: 5px;
margin: 0px auto;
position: fixed;
top: 0;
width: 100%;
height: 100%;
z-index: 1070;
overflow-x: hidden;
overflow-y: auto;
}
.lwp {
z-index: 1072;
position: absolute;
left: 0px;
right: 0;
top: 0;
bottom: 0px;
margin: 0px auto;
height: fit-content;
}
.lwp .loading {
text-align: center;
color: #FFF;
}
.lwp .loading .text {
color: #444;
}
.lwp #lwp {
margin: 0px auto;
background: #FFF;
border: 5px solid #000;
overflow-x: hidden;
overflow-y: hidden;
border-radius: 5px;
position: relative;
}
.lwp #lwpHead {
display: grid;
align-items: center;
grid-template-columns: 1fr 50px;
border-bottom: 1px solid #ddd;
}
.lwp #lwpHead .title {
font-weight: bold;
padding: 10px;
}
.lwp #lwpHead .close {
color: #fff;
font-size: 25px;
text-align: right;
cursor: pointer;
background: #000;
padding: 10px;
}
.lwp #lwpHead .close span {
position: relative;
left: -4px;
top: -5px;
}
.lwp #lwpBody {
overflow: auto;
}
.lwp #lwpClose {
float: right;
}
.lwp .clear {
clear: both;
}
.lwp-inline {
display: none;
}
.lwp-hidden {
overflow: hidden;
}
The HTML structure of the form. The below form does not function it is just an example you can create your own structure as per your need.
Remember: I am using Bootstrap 4 as a design framework. The below snippet is a bootstrap 4 code.
<div class="p-3">
<form method="post">
<div class="form-group">
<label>First Name</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Enter your first name">
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" name="name" id="name" class="form-control" placeholder="Enter your last name">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="name" id="name" class="form-control" placeholder="Enter your email">
</div>
<div class="form-group">
<label>Message</label>
<textarea rows="5" name="message" id="message" class="form-control" placeholder="Write your message here"></textarea>
</div>
<div class="form-group">
<input type="button" name="button" value="Submit" class="btn btn-danger">
</div>
</form>
</div>