How to append html content in bootstrap modal - javascript

I want to append html code in bootstrap modal
HTML content:
<div class="modal fade" id="share12" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content get_direction_modal_bg">
<div class="text-right"><a class="fa fa-times white normal12" data-dismiss="modal"> close</a></div>
<div class="modal-body">
<p class="white text-center">Share this Event</p>
<div class="share_list_popup">
<ul>
<li></li>
<li><a href="http://www.linkedin.com/shareArticle?mini=true&utm_campaign=201308&url=http://10times.com/"+eventname+"&title=Come join me at "+eventname+" on "+eventstartdate+","+eventcityname+".&utm_source=LinkedIn&source=LinkedIn
Come join me at "+eventname+" on "+eventstartdate+","+eventcityname+". Find event details at 10times.com/"+eventname+""></a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<img src="images/share.png">
Javascript code:
var modal_event_name=document.getElementById("modal_event_name");
var modal_event_startdate=document.getElementById("modal_event_name");
var modal_city_name=document.getElementById("modal_event_name");
$('#share12').modal('show');
The problem I'm getting:
modal is now working
guide how to show HTML content in bootstrap modal
JSFiddle: http://jsfiddle.net/4gW4y/115/

Bootstrap comes with methods for showing & hiding modals.
With bootstrap 3 you can do:
$("#pop").on("click", function() {
$('#imagemodal').modal('show');
$('#imagemodal').on('shown.bs.modal', function() {
$('#imagemodal').find('.modal-body').append('<p>append some html here</p>');
});
});

It looks like you're trying to use Javascript variables (eventname, eventstartdatae, eventcityname) directly in the HTML. Instead, you could try building the URL with Javascript, and set the <li> (list items) and <a href=""> (links) with jQuery:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
</head>
<body>
<div id="modal_event_name">My Event Name</div>
<div id="modal_event_startdate">My Event Start Date</div>
<div id="modal_city_name">My Event City Name</div>
<div class="modal fade" id="share12" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content get_direction_modal_bg">
<div class="text-right"><a class="fa fa-times white normal12" data-dismiss="modal">close</a></div>
<div class="modal-body">
<p class="white text-center">Share this Event</p>
<div class="share_list_popup">
<ul>
</ul>
</div>
</div>
</div>
</div>
</div>
<button onclick="showModal()">Show Modal</button>
Show Modal From Link
<script src="https://code.jquery.com/jquery-1.11.2.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script>
var eventname = document.getElementById("modal_event_name").textContent;
var eventstartdate = document.getElementById("modal_event_startdate").textContent;
var eventcityname = document.getElementById("modal_city_name").textContent;
var facebookLink = "https://www.facebook.com/?" + eventname + "&" + eventstartdate + "&" + eventcityname
var linkedinLink = "http://www.linkedin.com/?" + eventname + " & " + eventstartdate + "&" + eventcityname
$('.share_list_popup ul').append('<li>Facebook</li>');
$('.share_list_popup ul').append('<li>LinkedIn</li>');
function showModal() {
$('#share12').modal('show');
}
</script>
</body>
</html>
Working fiddle

There are several ways to manipulate the data of a modal (or anything else really). Bootstrap provides some, and you can read more about them there.
If you want to use jQuery below are some examples:
$("#pop").on("click", function() {
//ref. to the modal
var imgModal = $('#imagemodal');
//Shows the modal
imgModal.modal('show');
//ref. to the body of the modal
var imgModalBody = imgModal.find('.modal-body');
//Changes the entire content of the body, in the modal, to this
imgModalBody.html('<span style="color:red">This is appended directly from a string or variable</span><br/>');
//Appends a button to the modal body
imgModalBody.append(' <button id="clickMe">Load content from hidden div</button><br/>');
//Adds a click event on the button just appended
imgModal.on("click", "#clickMe", function() {
//Appends text from the hidden div, myHiddenContent, on the page
imgModalBody.append(' ' + $('#myHiddenContent').html());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
Open my modal
<div id="myHiddenContent" style="display:none;">This is appended from html already on the page (hidden or not)</div>
<!-- Modal -->
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Image preview</h4>
</div>
<div class="modal-body">
<img src="" id="imagepreview" style="width: 400px; height: 264px;" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Could you use a function to generate the hyperlinks?
E.g:
Link
function doSomething()
{
var modal_event_name=document.getElementById("modal_event_name");
var modal_event_startdate=document.getElementById("modal_event_name");
var modal_city_name=document.getElementById("modal_event_name");
var url="path?modal_event_name="+modal_event_name+"&modal_event_startdate="+modal_event_startdate + "&modal_city_name="+modal_city_name;
window.open(url,""."");
}
Something like this?

The modal is working with the code. Check if bootstrap js is included.
You can use the shown event of modal to add the variables.
var modal_event_name = "Event Name";
var modal_event_startdate = "10th july";
var modal_city_name = "SF"
$('#share12').modal('show');
$('#share12').on('shown.bs.modal', function () {
if (!$(this).hasClass('social-links-added')) {
$(this).addClass('social-links-added');
var linkedin_url = "http://www.linkedin.com/shareArticle?mini=true&utm_campaign=201308&url=http://10times.com/" + modal_event_name + "&title=Come join me at " + modal_event_name + " on " + modal_event_startdate + "," + modal_city_name + ".&utm_source=LinkedIn&source=LinkedIn Come join me at " + modal_event_name + " on " + modal_event_startdate + "," + modal_city_name + ". Find event details at 10times.com/" + modal_event_name;
var facebook_url = "https://www.facebook.com/sharer/sharer.php?u=www.10times.com&title=Come join me at" + modal_event_name + "on " + modal_event_startdate + ", " + modal_city_name;
$('.share_list_popup ul li:eq(0)').find('a').attr('href', facebook_url);
$('.share_list_popup ul li:eq(1)').find('a').attr('href', linkedin_url);
console.log(facebook_url);
console.log(linkedin_url);
}
});
Fiddle

Related

How to stop a youtube video after modal is dismissed?

After closing modal window the i frame element keeps playing and I don't have a clue how to refer to proper element in JS.
The trick is that I use PHP variable as an ID to generate and use multiple modal windows straight from my database.
The code goes as follows:
foreach ($movieId as $data) {
echo '<div class="card card-movie-poster bg-blacker text-white text-center text-align-middle mx-2 mb-3">
<div class="card-body">
<a data-toggle="modal" href="#myModal'.$data['movieID'].'"><img class="card-img " src="img/movieCovers/'.$data['datatitle'].'.jpg"></a>
</div>
</div>';}
And
foreach ($movieId as $datatitle) {
echo '<div class="modal fade" id="myModal'.$data['movieID'].'">
<div class="modal-dialog modal-lg modal-dialog-centered" role="document">
<div class="modal-content bg-black">
<div class="modal-header">
<!-- Movie Title -->
<h3 class="text-white-50">'.$data['movieTitle'].'</h3>
<!-- Close button -->
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body container">
<!-- Video -->
<div class="embed-responsive embed-responsive-16by9">
<iframe id="'.$data['movieID'].'" class="embed-responsive-item" src="https://www.youtube-nocookie.com/embed/'.$data['videoUrl'].'?rel=0&showinfo=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
';}
You can try:
$("#myModal").on('hidden.bs.modal', function (e) {
$("#myModal iframe").attr("src", $("#myModal iframe").attr("src"));
});
OK then.
Finally did it myself:
var grabbed = document.querySelectorAll('[id^="myModal"]');
var myModal;
var innerIframe;
for (var i = 0; i < grabbed.length; i++) {
// console.log(grabbed[i].id);
$(grabbed[i]).on('show.bs.modal', function () {
myModal = this.id;
// console.log(this.id);
})
$(grabbed[i]).on('hide.bs.modal', function () {
// console.log(this.id + " closed");
innerIframe = this.getElementsByClassName('embed-responsive-item');
$('iframe').attr('src', $('iframe').attr('src'));
// console.log(innerIframe[0]);
});
}

Using a button to open a page containing details of a stock item

My intention is to show products on the index page with links. When the link is clicked a 'modal' page opend showing the details of that product.
I have a button that links to a product page, but not the other items on the index page.
How do I use this link to open each product page?
The code for button:
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#details-1">Details</button>
The modal:
<?php
include 'details-modal-item01.php';
include 'details-modal-item02.php';
?>
The page details-modal-item01.php is more or less a template for the other items:
<div id="item01" class="modal fade item01" tableindex="-1" role="dialog" aria-labelledby="details-1" aria-hidden="true"> -- rest of code goes here --</div>
Any help will be appreciated.
Instead of all the include jazz, which will become unmanageable once you got many products you should use ajax to load the content/partial or build from json into the modal-content section.
Ok easy said then done, so here is an example.
This is genrally how I do it, by using ajax and partials.
The Link(s), you would need to change the data-url="" attribute to point to your partial.
<i class="fa fa-plus fa-fw"></i> Open Modal
The modal wrapper. This would be placed at the bottom of your template, before </body>.
<div id="ajax-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Loading...</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true" aria-label="Close">×</button>
</div>
<div class="modal-body slow-warning"><p>Please wait...</p></div>
</div>
</div>
</div>
The partial, would be served from the links endpoint, you could check the request is ajax and show the partial and if its not show a full page instead.
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Foo Bar</h4>
</div>
<div class="modal-body"></div>
</div>
Then the jquery, which handles loading the content into the modal.
<script>
var ajax_modal = function(e) {
e.preventDefault();
$('#ajax-modal').modal('show');
var modal = '.modal-content';
var default_content = '' +
'<div class="modal-header">' +
' <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-times"></i></button>' +
' <h4 class="modal-title">' +
' Loading...' +
' </h4>' +
'</div>' +
'<div class="modal-body">' +
' <p class="slow-warning">Please wait...</p>' +
'</div>';
$(modal).html(default_content);
setTimeout(function() {
if ($(document).find('.slow-warning').length > 0) {
$(document).find('.slow-warning').html('Content failed to load, please refresh your browser and try again.');
}
}, 5000);
//
var dialog_size = $(this).data('size');
if (dialog_size == 'modal-lg') {
$(modal).parent().removeClass('modal-sm modal-md modal-lg').addClass('modal-lg');
}
else if (dialog_size == 'modal-sm') {
$(modal).parent().removeClass('modal-sm modal-md modal-lg').addClass('modal-sm');
}
else {
$(modal).parent().removeClass('modal-sm modal-md modal-lg').addClass('modal-md');
}
//
var request = $.ajax({
url: $(this).data('url'),
method: "GET",
dataType: "html",
cache: false
});
request.done(function(data) {
$(modal).replaceWith($('<div />').html(data).find(modal)[0]);
});
request.fail(function(jqXHR, textStatus) {
console.log('modal failed to load', textStatus);
});
};
$(document).find('.ajax-modal').off('click').on('click', ajax_modal);
</script>

Bootstrap Modal and Badges

I have the following lines of code in my webpage - example/demo.
HTML:
<p data-toggle="modal" data-target="#messagesModal">Messages <span class="badge">2</span>
</p>
<!-- Modal -->
<div class="modal fade" id="messagesModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Messages</h4>
</div>
<div class="modal-body">
<div class="alert fade in">
×
<strong>Message 01</strong>:
<p>Lipsum Ipsum
</p>
</div>
<div class="alert fade in">
×
<strong>Message 02</strong>:
<p>Ipsum Lipsum</p>
</div>
</div>
<div class="modal-footer">
<div class="col-md-8 pull-left">
</div>
<div class="col-md-4">
<button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
How can I update the badge to represent the correct amount of messages in the modal?
For example, when the user closes or removes a message in the modal, the badge will go from displaying the number 2 to 1?
Also, is it possible to display the text "There are no more messages." when all of the messages have been removed?
Try this:
//Find message number initially, before editing
$(".badge").text($(".alert").length);
//when the modal is closed
$('#messagesModal').on('hidden.bs.modal', function () {
//Set .badge text equal to the length of the .alert array, i.e the number of messages
$(".badge").text($(".alert").length);
//If there are no '.alert' divs, i.e. no messages
if ($(".alert").length == 0) {
$(".badge").text("No messages");
}
});
This takes all the .alert elements (messages) into an array, and sees how long that array is (i.e. how many messages there are).
Then, it updates .badge to reflect that number.
Working JSFiddle: http://jsfiddle.net/joe_young/62hbqmtp/
Well... I've spend some time, but all that you should do for now:
populate message array with your actual data;
add some actual AJAX for removing messages.
So...
$(function() {
var informer = $("#messageInformer a");
var refreshBadge = function(messageCount) {
var badge = informer.find(".badge");
if (messageCount > 0) {
if (!badge.length) {
informer.text("Messages ");
informer.append("<span class=\"badge\">" + messageCount + "</span>");
} else {
badge.text(messageCount);
}
} else {
informer.text("No messages");
}
};
var buildMessage = function(message) {
var htmlMessage = "<div class=\"alert fade in\">";
htmlMessage += "×";
htmlMessage += "<strong>" + message.title + "</strong>:";
htmlMessage += "<p>" + message.text + "</p>";
return htmlMessage;
}
// There should be real data
var messages = [
{ id: "1", title: "Message 01", text: "Lipsum Ipsum" },
{ id: "2", title: "Message 02", text: "Ipsum Lipsum" }];
refreshBadge(messages.length);
informer.on("click", function(e) {
e.preventDefault();
var modalBody = $(".modal-body");
modalBody.empty();
for (var i = 0; i < messages.length; i++) {
modalBody.append(buildMessage(messages[i]));
}
});
$("body").delegate(".alert .close", "click", function() {
var messageId = $(this).data("id");
// There should be some AJAX possibly
messages = messages.filter(function(el) {
return el.id != messageId;
});
if (messages.length == 0) {
$("#messagesModal").modal("hide");
}
refreshBadge(messages.length);
});
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<p data-toggle="modal" data-target="#messagesModal" id="messageInformer">Messages <span class="badge"></span>
</p>
<!-- Modal -->
<div class="modal fade" id="messagesModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Messages</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<div class="col-md-8 pull-left">
</div>
<div class="col-md-4">
<button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>

How to load image into Bootstrap Modal from JSON Flickr API

Below is the code I am working with as an example.
When I click each image from the Flickr feed I want to be able to load the Bootstrap Modal (which it does) but display that particular photo in the Modal (which it currently doesnt).
I've tried numerous different things. But I am unable to get it to work.
Example at http://jahax.com/ins/
<div class="container">
<h2 style="text-align: center;">Demonstration</h2>
<p class="text-center">Demo of Bootstrap, jQuery & JSON API</p>
<div class="row text-center">
</div>
<div id="images" class="row text-center"> </div>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="nyModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<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="myModalLabel">Demo of Modal</h4>
</div>
<div class="modal-body">
<img id="mimg" src="">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
// Start jQuery Function
$(document).ready(function(){
// JSON API to access Flickr
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=winter&format=json&jsoncallback=?", displayImages);
function displayImages(data) {
var iCount = 0;
var htmlString = "<div class=row>";
$.each(data.items, function(i,item){
if (iCount < 18) {
var sourceSquare = (item.media.m).replace("_m.jpg", "_q.jpg");
htmlString += '<a class="btn" data-toggle="modal" data-target="#myModal">';
htmlString += '<img src="' + sourceSquare + '">';
htmlString += '</a>';
}
iCount++;
});
// HTML into #images DIV
$('#images').html(htmlString + "</div>");
// Close down the JSON function call
}
// End jQuery function
});
</script>
<script type="text/javascript">
// Send Content to Bootstrap Modal
$('img').on('click',function()
{
var sr=$(this).attr('src');
$('#mimg').attr('src',sr);
$('#myModal').modal('show');
});
</script>
Change your 2nd script to this:
<script type="text/javascript">
// Send Content to Bootstrap Modal
$(document).on('click', 'img', function(){
var sr=$(this).attr('src');
$('#mimg').attr('src',sr);
$('#myModal').modal('show');
});
</script>

Try to get bootstrap modal carousel caption to appear

Ultimately I'm try to get the caption and author to display below the image.
Here is the html:
<div class="row">
<div class="col-lg-3 col-sm-4 col-6"><img src="//placehold.it/600x350" class="thumbnail img-responsive"></div>
<div class="col-lg-3 col-sm-4 col-6"><img src="//placehold.it/600x350/2255EE" class="thumbnail img-responsive"></div>
</div>
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Heading</h3>
</div>
<div class="modal-body">
<p class="modal-caption"></p>
</div>
<div class="modal-footer">
<button class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
And the javascript. I just don't know what I'm doing wrong, so any help would be awesome. I'm trying to access the data-attributes inside of the anchor tags to populate the corresponding divs (data-caption would display in .).
// Gallery Modal
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
var caption = $(this).parent('a').attr("data-caption");
$('.modal-caption').html(caption);
item.attr("data-caption",caption);
item.appendTo('.modal-caption');
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
In your code item is not defined.
Try this instead: Takes data-caption and data-author and creates matching elements.
Narrows down the jQuery selectors, constructs jQuery selections only once if applicable and uses $.fn.text for better performance.
Working Fiddle: http://jsfiddle.net/9NYNW/1/
$('.thumbnail').click(function(){
var $parent = $this.parent('a');
var $modal = $('#modal');
var $title = $modal.find('.modal-title');
var $body = $modal.find('.modal-body');
var $items = $();
$.each(['caption', 'author'], function(i, key) {
var $item = $('<div />', { 'class': 'modal-' + key });
$item.text($parent.attr('data-' + key));
$items = $items.add($item.get(0));
});
$title.text($parent.attr('title'));
$body.html($(this).clone());
$body.append($items);
$modal.modal({show:true});
});

Categories