How to generate a Twitter Bootstrap modal but keep it hidden - javascript

I want to create a Twitter Bootstrap modal, but keep it hidden until I'm ready to show it.
Here is the smallest amount of code to demonstrate. It successfully creates the modal, but it applies display: block to it inline, overriding my style.
modalHtml = '<div class="modal fade" style="display: none" tabindex="-1" role="dialog" id="myModal">'
+ '<div class="modal-dialog modal-lg" role="document">'
+ '<div class="modal-content">Hello World</div></div></div>'
modal = jQuery(modalHtml);
modal.modal('show');
https://jsfiddle.net/Lx23xqbq/2/
I could add this
modal.modal('hide');
But this allows the modal to be visible for a split second.
How can I create a Twitter Bootstrap modal without displaying it to the user?

Modals are hidden via the CSS class .modal by default.
Remove modal.modal( 'show' );.
You have modal.modal( 'show' ); in your JS which causes the modal to be visible for a split second before you call modal.modal( 'hide' ).
Personally I would place the modal markup into the page before hand.
var $button = $('button');
var $modal = $('#myModal');
$modal.on('show.bs.modal', function(e) {
// Optional. We update the modal with content stored in the data-content
// attribute of the <button>.
// You could also grab another hidden element to inject or perform
// AJAX here.
var content = $(e.relatedTarget).data('content');
$modal
.find('.modal-content')
.text(content);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<button type="button" data-toggle="modal" data-target="#myModal" data-content="Hi Guy!">Show Modal</button>
<div class="modal fade" style="display: none" tabindex="-1" role="dialog" id="myModal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">Hello World</div>
</div>
</div>
Injecting into the page wouldn't be much different.
var html =
'<div class="modal fade" style="display: none" tabindex="-1" role="dialog" id="myModal">' +
'<div class="modal-dialog modal-lg" role="document">' +
'<div class="modal-content">Hello World</div>' +
'</div>' +
'</div>';
// Append modal markup to page.
$('body').append(html);
var $button = $('button');
var $modal = $('#myModal');
$modal.on('show.bs.modal', function(e) {
// Optional. We update the modal with content stored in the data-content
// attribute of the <button>.
// You could also grab another hidden element to inject or perform
// AJAX here.
var content = $(e.relatedTarget).data('content');
$modal
.find('.modal-content')
.text(content);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<button type="button" data-toggle="modal" data-target="#myModal" data-content="Hi Guy!">Show Modal</button>

How can I create a Twitter Bootstrap modal without displaying it to
the user?
Technically you are already creating the modal with your first 2 lines of code. It just isn't displayed until the 3rd line (modal.modal('show');).
What I think you might be trying to accomplish is separating the code that creates the modal from the code that shows/hides it. The problem (I'm assuming) is that elsewhere in your code you no longer have a reference to the variable modal (that you created in modal = jQuery(modalHtml);), because it is out of scope.
Add this to your HTML page:
<div id="hidden-modal" style="display:none"></div>
Update your Javascript as described below:
modalHtml = '<div class="modal fade" style="display: none" tabindex="-1" role="dialog" id="myModal">'
+ '<div class="modal-dialog modal-lg" role="document">'
+ '<div class="modal-content">Hello World</div></div></div>'
// inject the modal markup into the hidden element on the page
jQuery('#hidden-modal').html(modalHtml);
// whenever ready, retrieve the hidden modal html and display it
jQuery(jQuery('#hidden-modal').html()).modal('show');
https://jsfiddle.net/Lx23xqbq/3/

If I understand your question this have to work:
$(document).ready(function () {
draw();
});
function draw() {
var html = ""
html += '<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>';
html += '<hr />';
html += '<div id="myModal" class="modal fade" role="dialog">';
html += '<div class="modal-dialog">';
html += '<div class="modal-content">';
html += '<div class="modal-header">';
html += '<button type="button" class="close" data-dismiss="modal">×</button>';
html += '<h4 class="modal-title">Modal Header</h4>';
html += '</div>';
html += '<div class="modal-body">';
html += '<p>Some text in the modal.</p>';
html += '</div>';
html += '<div class="modal-footer">';
html += '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
html += '</div>';
html += '</div>';
html += '</div>';
html += '</div>';
$('#modal').html(html);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div id="modal">
</div>
When page is loaded the function draw() draws the modal and keep it hidden until you click the button, hyperlink, label or whatever you want.

Related

Jquery.load HTML and insert into bootstrap modal

I'm kind of stuck at the moment. Would really appreciate if someone can help me with this.
First time asking a question, so please bear with me :)
I have a main page with a few buttons. Each button opens a bootstrap modal. I am able to load dynamic content into the modal. Also inserting external HTML works, but here's the catch.... The HTML content I insert also has some 'fancy' features like my main page has (ex. animated progress bar/skills) For the external HTML to work I need to reference the same script as my main page has, but if so, things on my main page gets broken.
My question is, is there any way that I can insert HTML into my modal and have the inserted HTML be able to use the existing functions on my main page?
var iModal = document.getElementById('iModal');
iModal.addEventListener('show.bs.modal', function handler() {
// Button that triggered the modal
var button = event.relatedTarget;
var modalTitleArg = button.getAttribute('data-bs-title');
var modalId = button.getAttribute('data-bs-id');
var modalTitle = iModal.querySelector('.modal-title');
var modalBody = iModal.querySelector('.modal-body');
modalTitle.textContent = modalTitleArg;
if (modalId == 1) {
$('.modal-body').load('Content1.html', function() {
$.getScript("js/functions.js") //get script, modal works, broken mainpage.
});
} else if (modalId == 2) {
$('.modal-body').load('Content2.html', function() {
//$.getScript("js/functions.js") //script reference in html, modal works broken mainpage
});
} else {
$('.modal-body').load('Content3.html', function() {
//$.getScript("js/functions.js") // no script at all, broken modal, mainpage works fine
});
}
this.removeEventListener('show.bs.modal', handler);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-outline-light mt-2" data-bs-toggle="modal" data-bs-target="#iModal" data-bs-id="1" data-bs-title="Title1">Click me 1</button>
<button type="button" class="btn btn-outline-light mt-2" data-bs-toggle="modal" data-bs-target="#iModal" data-bs-id="2" data-bs-title="Title2">Click me 2</button>
<button type="button" class="btn btn-outline-light mt-2" data-bs-toggle="modal" data-bs-target="#iModal" data-bs-id="3" data-bs-title="Title3">Click me 3</button>
<!-- modal -->
<div class="modal fade" id="iModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="myModalLabel">Title</h3>
<!-- data-bs-title -->
<button type="button" class="btn-close btn-sm" data-bs-dismiss="modal" aria-hidden="true"></button>
</div>
<div class="modal-body">
<!-- external html content -->
</div>
<div class="modal-footer">
<button type="button" class="btn-close btn-sm" data-bs-dismiss="modal" aria-hidden="true"></button>
</div>
</div>
</div>
</div>
<script src="js/functions.js"></script>
If in your "Content1.html", "Content2.html" etc. there is already an attached <script src="js/functions.js"></script> (as in a simple web page), then you can add content simply through an iframe tag (via the src attribute). Sample part of the code from your example:
...
<div class="modal-body">
<iframe class="modal-body-frame"></iframe>
</div>
...
<script>
...
const modalFrame = document.querySelector('.modal-body-frame');
if (modalId === 1) modalFrame.src = 'Content1.html';
...
</script>
...
But if you need to embed the script into the content every time, then you can use the srcdoc attribute of the iframe tag. Example below:
...
<div class="modal-body">
<iframe class="modal-body-frame" srcdoc=""></iframe>
</div>
...
<script>
...
const modalFrame = document.querySelector('.modal-body-frame');
if (modalId === 1) {
$.get('Content1.html', function(data) {
modalFrame.srcdoc = data.replace('</head>', '<script src="js/functions.js"></script></head>');
})
}
...
</script>
...
When using frame, it is important not to forget about Feature Policy and the ability to add permission via the allow attribute (Example: <iframe srcdoc="<p>Example test page</p>" allow="fullscreen"></iframe>).

Onclick pass value to popup modal

I have created a dynamic table and in that table I have a link which should trigger a popup modal.
And I have tried to pass the value to modal popup with "onclick", but the value still didn't show in the modal popup
Here is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../css/style.css">
<link href="../libraries/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link rel="stylesheet" href="../libraries/css/jquery-ui.css">
<script src="../libraries/js/jquery-1.10.2.js"></script>
</head>
<?php
$sql="select * from tbl_company";
$query=mysql_query($sql);
while($row=mysql_fetch_assoc($query)){
$code=$row['code'];
$name=$row['name'];
?>
<span id="myBtn" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" onclick="getCompanyCode('<?php echo $code;?>','<?php echo $name;?>')"><img src="../images/edit.png" style="width:20px;"></span>
<?php
}
?>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">X</span>
<input id="company" name="company" type="text" value="" readonly></td>
<input id="codes" name="codes" type="text" value="">
</div>
</div>
<script>
function getCompanyCode(str,nm) {
alert(str,nm);
var val_name = nm;
var val_code = str;
document.getElementById("company").value = val_name;
document.getElementById("codes").value = val_code;
}
</script>
<script type="text/javascript">
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
To open a modal window, you should use data-toggle="modal" and href. If it's not <a>, you can use data-target instead:
data-toggle="modal" data-target="#exampleModal"
To pass a unique value to the modal, you need to use data-* attributes. This can be given to the modal handler like this:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="#mdo">Open modal for #mdo</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="#fat">Open modal for #fat</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="#getbootstrap">Open modal for #getbootstrap</button>
The next thing is that, you need to handle the custom input. Once the modal window is shown, you need to execute some stuff. For that, you need to assign an event handler, once the modal window is shown:
// Execute something when the modal window is shown.
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var recipient = button.data('whatever'); // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this);
modal.find('.modal-title').text('New message to ' + recipient);
modal.find('.modal-body input').val(recipient);
});
The issues with your code:
Assigning multiple elements with same id is a crime. Do not reuse id as they are unique.
You need to assign the data-toggle to the <a> tag.
You should pass the attributes through data-* attributes.
Working Snippet
$(function () {
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var code = button.data('code'); // Extract info from data-* attributes
var company = button.data('company'); // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this);
modal.find('#code').val(code);
modal.find('#company').val(company);
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<a href="#myModal" class="btn btn-info btn-lg" data-toggle="modal" data-code="code" data-company="company name">
<img src="../images/edit.png" style="width:20px;">
</a>
<div class="modal fade bs-example-modal-sm" tabindex="-1" id="myModal">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="mySmallModalLabel">Codes & Company</h4>
</div>
<div class="modal-body">
<input type="text" id="code" readonly />
<input type="text" id="company" readonly />
</div>
</div>
</div>
</div>
Please map your code with the above code. You don't need to change any other values. Just the way <span> is done.

Modal content not loaded using jQuery

I am trying to make an instruction page about proxy settings for the users.
I have listed procedures step by step for each browser and put a link to picture that shows how it is done.
I want to show the picture in an PHP file which getting required image file and showing on the page according to its parameters s and b which are stand for s: step and b: browser.
My jQuery is
$(function() {
$("a[id^='proxy_']").click(
function() {
var b = $(this).data("b");
var s = $(this).data("s");
$("#proxy_modal_title").html("Proxy Settings");
$("#proxy_modal_body").load("images/proxy_settings/proxy.php?b=" + b + "&s=" + s);
});
});
It should load ./images/proxy_settings/proxy.php?b=ie&s=1 but nothing happens.
And HTML is ( a part only)
<ol>
<li>Click on Settings <a id="proxy_ie_step_01" data-s="1" data-b="ie" href="#proxyModal" data-toggle="modal" title="Show picture"> <span class="glyphicon glyphicon-picture"></span></a>
</li>
<li>Select Internet Options <a id="proxy_ie_step_02" data-s="2" data-b="ie" href="#proxyModal" data-toggle="modal" title="Show picture"> <span class="glyphicon glyphicon-picture"></span> </a>
</li>
<!-- goes on -->
</ol>
And the modal is here:
<div class="modal fade" id="proxyModal" tabindex="-1" role="dialog" aria-labelledby="zkanoca" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="proxy_modal_title"></h4>
</div>
<div class="modal-body" id="proxy_modal_body">
</div>
</div>
</div>
</div>
Proxy.php file content is here:
if (isset($_GET['b']) && isset($_GET['s']))
{
echo '<img src="proxy_setting_' . $_GET['b'] . '_' . $_GET['s'] . '.png " />';
}
else
{
exit;
}
Modal opens up but either modal title or modal content are empty. I have checked it with Firebug but cannot see any error.
I have tried to put an alert("HEY"); into $("a[id^='proxy_']").click(); event. It also did not work.
If it was a path issue, Firebug would have given me a 404 error.
The file structure tree is like the following:
|.
|-js
|-script.js
|-images
|-proxy_settings
|-proxy.php
|-proxy_setting_ie_1.png
|-proxy_setting_ie_2.png
|-proxy_setting_ie_1.png
|-proxy_setting_ie_3.png
|-proxy_setting_ie_4.png
|-proxy_setting_ie_5.png
|-proxy_setting_ie_6.png
|-proxy_setting_ie_7.png
|-instructionpage.html
|-messageform.php
|-index.php
The script does not listen click events although it responds another same event:
This works which resides at the same file (script.js):
jQuery("#sendMessage").click(
function() {
jQuery("#sendmessage_modal_title").html("Send A Message");
jQuery("#sendmessage_modal_body").load("messageform.php");
});
If the li elements are generated dynamically, you should try this:
$(document).on("click", "a[id^='proxy_']", function () {
//
});
First of all I apologize you all wasting your valuable time.
I was trying to retrieve the instructions.html into index.php using jQuery's load() function. I moved
$(function() {
$("a[id^='proxy_']").click(
function() {
var b = $(this).data("b");
var s = $(this).data("s");
$("#proxy_modal_title").html("Proxy Settings");
$("#proxy_modal_body").load("images/proxy_settings/proxy.php?b=" + b + "&s=" + s);
});
});
to instructions.html's itself then the problem is gone.
your .php files is in the folder images/proxy_settings/
maybe in your proxy.php file change the img src to: echo '<img src="../proxy_setting_' . $_GET['b'] . '_' . $_GET['s'] . '.png " />';
Update:
I dont know why but my Firebug tell me the 404 Not Found Error!
Replace this code into the proxy.php and it should work.
echo '<img src="images/proxy_setting_' . $_GET['b'] . '_' . $_GET['s'] . '.png " />';

Pass a variable for use as a href attribute in a modal

I want to pass a url to be used in my modal which relies on getting the adder variable from my main HTML document. I know how to pass variables to a modal to be used as text (using span) but not sure how to use a variable in a link <a href> tag.
I have bolded the areas in each document that are important. Javascript gets the adder variable from the main HTML document and stores it as URL.
MAIN HTML DOCUMENT:
<span id = "modelname"> {{symbol.modelname.upper}}</span> - <span id = "format">{{ symbol.format }}</span>**<span id = "adder" style="visibility:hidden;"> {{symbol.adder}}</span>**
JAVASCRIPT:
<script type="text/javascript">
$(document).on("click", ".lib", function () {
var modelname = $('#modelname').text();
$('#modelnameplaceholder').replaceWith(modelname);
var format = $('#format').text();
$('#formatplaceholder').replaceWith(format);
var adder = $('#adder').text();
$('#adderplaceholder').replaceWith(adder);
**var URL = "/profiles/profile/" + adder + "/"**
$('#urlplaceholder').replaceWith(URL);
var type = $(this).closest("ul").attr('id');
$('#typeplaceholder').replaceWith(type);
$('#myModal').modal('show');
});
</script>
MODAL DIALOG:
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel"><span id="modelnameplaceholder"></span> <span id="typeplaceholder"></span> for <span id="formatplaceholder"></span></h3>
</div>
<div class="modal-body">
<div style="background-image: url({{ STATIC_URL }}pinax/images/placeholder.png); background-repeat:no-repeat;background-position:center center; height: 300px; width: 100%; "></div>
<br>
<div id = "download-button" style="text-align-center">
<i class="icon-download icon-white"></i> Download {{item.type}}
</div>
<br>
<br>
<br>
<div style="position:0px;float:right;">
**Added by </span>**
I want to make the Added by <username> link to the url that is passed from javascript.
How would I do this?
This should work
var url = "http://google.com/";
$("#a").href = url;

twitter bootstrap dynamic show modal - too much recursion error

i have jQuery v1.8.3 and twitter-bootstrap v2.2.1
I want to create a function to dynamically display the message.
function showMsg(header, text, closeFunc) {
var randId = Math.round(Math.random()*1000000);
var dialog = '<div id="modal_' + randId + '" class="modal hide fade">';
dialog += '<div class="modal-header">';
dialog += '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>';
dialog += '<h3>' + header + '</h3>';
dialog += '</div>';
dialog += '<div class="modal-body">';
dialog += text;
dialog += '</div>';
dialog += '<div class="modal-footer">';
dialog += '<button id="modalBtn_' + randId + '" class="btn btn-primary">Close</button>';
dialog += '</div>';
dialog += '</div>';
$('body').append(dialog);
var modal = $('#modal_' + randId);
modal.modal({backdrop : false, show : false, keyboard : false});
modal.modal('show');
var btn = $('#modalBtn_' + randId);
btn.click(function(){
closeFunc();
modal.modal('hide');
});
}
But after display more than 3 these messages at once I get an error in Jquery: too much recursion
How can I fix it or have another way?
I couldn't recreate your "too much recursion" error, but I did want to suggest a better way of doing dynamic messages than the code you currently have. Namely, you could just be using a single Modal and update the content in it before showing it. That would eliminate all the overhead you're presently incurring by
having jQuery parse the same string into html repeatedly;
instantiating a new Modal object for every message; and
generating random id's and then searching through the DOM for elements created with them.
As an alternative, have the following blank Modal in the markup from the start. Doesn't really matter where, but bottom of the <body> is a typical location. If you must generate it dynamically, do it outside the showMsg function and do it only once.
<div id="msgModal" class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3></h3>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button class="btn btn-primary callback-btn" data-dismiss="modal">Close</button>
</div>
</div>
Notice I did make some alterations from yours by adding the fixed id="msgModal" to the modal and added the class callback-btn and attribute data-dismiss="modal" to the button.
Then the code for showMsg could be:
var $msgModal = $('#msgModal').modal({
backdrop: false,
show: false,
keyboard: false
}),
showMsg = function (header, body, callback) {
$msgModal
.find('.modal-header > h3').text(header).end()
.find('.modal-body').text(body).end()
.find('.callback-btn').off('click.callback')
.on('click.callback', callback).end()
.modal('show');
};
Here's a demo which outputs to the console if the footer button is clicked:
Plnkr
Or just trigger this event :
jQuery('Click me !').trigger('click.modal.data-api');

Categories