Bootstrap Modal - show does not remove hide attribute - javascript

I am creating a Bootstrap 2.3.1 modal as follows:
myModal = $('<div/>', {
'class': 'modal hide',
'id': id + '-addModal',
'tabindex': -1, // needed for escape to work...
'role': 'dialog',
'data-backdrop': 'static'
}).append(content);
// insert Modal into DOM...
$(jqElement).after(myModal);
// focus on first input when it pops up...
myModal.on('shown', function () {
myModal.find('select:first').focus();
});
// in response to button click...
myModal.modal('show');
On rare occasions, the backdrop shows, but no modal is displayed. Has anyone encountered a similar problem and a workaround? I am aware IE8 does not like animated modals (use of fade class) and this doesn't appear to be the same issue as we don't use fade. The issue appears in FF, Chrome and IE, but like the Spanish Inquisition, never when I'm expecting it.
The failure appears to be within the modal('show') execution. It seems that the modal exists but is not unhidden. I believe this should be achieved by adding the in class to the modal. The show and shown events do occur however. From looking at the bootstrap code, the fact that the shown event occurs means that the event is not prevented from default behaviour.
Note This is a question similar to one I posted earlier, but I have added some more information concerning how it fails.
Please also note that I cannot update to Bootstrap 3. I am responsible for making small changes to an already released product and a change of basic libraries is a non-starter.

I've modified the code and appended to the body instead of the unknown jqElement specified in your example. I've also added some example place holder content. See the following JS Fiddle for a working example http://jsfiddle.net/kYVtf/5/
var id = 'test',
content = '<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="myModalLabel">Modal header</h3></div><div class="modal-body"><p><select><option>TEST</option></select></p></div> <div class="modal-footer"> <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button> </div>';
var myModal = $('<div/>', {
'class': 'modal hide fade',
'id': id + '-addModal',
'tabindex': -1, // needed for escape to work...
'role': 'dialog',
'data-backdrop': 'static'
}).html(content);
// insert Modal into DOM...
$('body').append(myModal);
// focus on first input when it pops up...
myModal.on('shown', function () {
myModal.find('select:first').focus();
});

I found the following issues helped:
a) The 'shown' action of the modal checks for a display:block attribute and forces it to be set.
b) the close button (which needed to do validation) was set to a click event - changing this to a delegated event made it work reliably
c) both the cancel buttons were mapped to the modal-dismiss action.
myModal.on('show', function (event) {
self._debug("show modal");
// show add form - should be a modal
myModal.find('form')[0].reset();
myModal.find('.alerts').empty();
self._debug('show end');
return true;
});
myModal.on('shown', function () {
var $el = $('#myModal');
if ($el.css('display') == 'none') {
self._debug(" WARNING! modal css error");
}
self._debug("fix for bootstrap error");
$el.css('display', 'block');
myModal.find('select:first').focus();
self._debug('Shown modal');
return true;
});
myModal.on('hide', function () {
self._debug('Hide modal');
return true;
});
myModal.on('hidden', function () {
var $el = $('#myModal');
$el.css('display', 'none');
self._debug('Hidden modal');
return true;
});

This behaviour started happening for me after I added the following to prevent unhandled modal closure.
$('.modal').modal({
backdrop: 'static',
keyboard: false
});
I fixed it by adding show: false to the modal options and making sure there was no hide class in <div class="modal fade"

Related

Multiple bootstrap popovers on page but only the first one that's clicked works as desired

I have multiple popovers which are placed in different cells of a jquery datatable.
//popover needs to be triggered onclick on this i element
<i tabIndex ="0" class="fa fa-info-circle popoverIcon" aria-hidden="true" data-placement="bottom" data-toggle="popover" ></i>
//this is hidden by css
<div class="popover-content hidden"><div>Popover text</div></div>
Popover initialization:
$('#MyDataTable').on('mouseenter', '.popoverIcon', function (event) {
$(this).popover({
html: true,
content: function () {
return $(this).next().html();
},
title: "Comment",
trigger: "manual"
});
});
I want the popover to have all trigger: "click" functionality, but be dismissable by clicking OUTSIDE the popover element area (popover area = the popover box itself or the mentioned i element). I have applied a solution I found here How to dismiss a Twitter Bootstrap popover by clicking outside?
It looks like that. The function to SHOW popover:
$('#MyDataTable').on('click', '.popoverIcon', function (event) {
//if popover closed - open it
if (!popoverOpen) {
$(this).popover('toggle');
popoverOpen = true;
}
});
The function to HIDE popover:
$(document).on('click', function (e) {
if (popoverOpen && !mouseOnPopoverArea) {
$('[data-toggle="popover"]').each(function () {
if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
$(this).popover('hide');
}
});
popoverOpen = false;
}
});
The strange thing is, it works perfectly, but ONLY with the very first popover I open. When I try to open the second, third, fourth (...) one, nothing is happenning. When I go back to the first one I clicked, it works again. What could be the matter?
$('#MyDataTable').on('click', '.popoverIcon', function (event) {
//if popover closed - open it
if (!popoverOpen) {
$(this).popover('toggle');
popoverOpen = true;
}
});
in this you are calling on click event on only one id so try to assign different ids and on click events on them accordingly
Try to access the pop over by first targeting it's parent element using parent() through $this and then finding the pop over element in it using find()

How to set custom click event handler for data-toggle="modal" button without opening modal dialog?

I have a $.post() request named "HasIncreasePoint" and if the data returned from server indicates a success (e.IsSuccess), I want not to open the bootstrap modal dialog, and accomplish the click event process.
$('a[data-toggle="modal"]').on('click', function (event) {
$.post("#Url.Action("HasIncreasePoint")", function (e){
if (e.IsSuccess) {
alert("error!please not to open the modal!");
event.preventDefault();
event.stopPropagation();
$('a[data-toggle="modal"]').off("click");
}else{
// From the clicked element, get the data-target arrtibute
// which BS3 uses to determine the target modal
var target_modal = $(e.currentTarget).data('target');
// also get the remote content's URL
var remote_content = e.currentTarget.href;
// Find the target modal in the DOM
var modal = $(target_modal);
// Find the modal's <div class="modal-body"> so we can populate it
var modalBody = $(target_modal + ' .modal-body');
// Capture BS3's show.bs.modal which is fires
// immediately when, you guessed it, the show instance method
// for the modal is called
modal.on('show.bs.modal', function () {
// use your remote content URL to load the modal body
modalBody.load(remote_content);
}).modal();
// and show the modal
// Now return a false (negating the link action) to prevent Bootstrap's JS 3.1.1
// from throwing a 'preventDefault' error due to us overriding the anchor usage.
return false;
}
});
});
and the HTML code:
<a class="btn-check-in" href="#Url.Action("ReverseCard")" data-toggle="modal" data-target="#myModal" id="btn-sign">
<i></i><span>SignIn</span>
</a>
You can remove data-toggle="modal" attribute and bind click on .btn-check-in class.
Then, whenever you need the modal, open it using javascript (as you already do)
<a class="btn-check-in" href='#Url.Action("ReverseCard")' data-target="#myModal" id="btn-sign">
<i></i><span>SignIn</span>
</a>
JS:
// set a flag to prevent multiple requests:
var waiting = 0;
$('.btn-check-in').on('click', function(event){
event.preventDefault();
if(!waiting){
var myModal = $(this).data('target');
var remote_content = this.href;
$.post('#Url.Action("HasIncreasePoint")').done(function(e){
if(!e.IsSuccess){
// this part seems to be overdone, but I left it as is
// as I don't know what is your reason of loading fresh content each time...
$(myModal).on('show.bs.modal', function(){
$(this).find('.modal-body').load(remote_content);
}).modal('show');
}else{
// it was successful!
}
waiting = 0;
});
}
waiting = "I'm waiting for $.post()";
});

Capturing 'shown' event from bootstrap tab

I have some 'static' HTML on my page:
<div id="DIVISIONS">
<ul class="nav nav-tabs" id="DIVISIONTABS">
#* <li> nodes will be injected here by javascript *#
</ul>
<div class="tab-content" id="DIVISIONTABPANES">
#* <div class="tab-pane"> nodes will be injected here by javascript *#
</div>
</div>
On page load, I create a tab 'framework', i.e. create the bootstrap tabs and tab content containers.
I trigger the process with:
$(window).bind("load", prepareDivisionTabs);
And "prepareDivisionTabs" does this:
function prepareDivisionTabs() {
// Retrieve basic data for creating tabs
$.ajax({
url: "#Url.Action("GetDivisionDataJson", "League")",
cache: false
}).done(function (data) {
var $tabs = $('#DIVISIONTABS').empty();
var $panes = $('#DIVISIONTABPANES').empty();
for (var i = 0; i < data.length; i++) {
var d = data[i];
$tabs.append("<li>" + NMWhtmlEncode(d.Name) + "</li>");
$panes.append("<div id=\"TABPANE" + d.DivisionId + "\" class=\"tab-pane\"></div>")
}
renderDivisionTabPaneContents(data);
}).fail(function (err) {
alert("AJAX error in request: " + JSON.stringify(err, null, 2));
});
}
For info, the "renderDivisionTabPaneContents" in the above does this:
function renderDivisionTabPaneContents(data) {
for (var i = 0; i < data.length; i++) {
var d = data[i];
renderDivisionTabPaneContent(d.DivisionId);
}
}
function renderDivisionTabPaneContent(id) {
var $tabPane = $('#TABPANE' + id);
$tabPane.addClass("loader")
$.ajax({
url: "/League/GetDivisionPartialView?divisionId=" + id,
cache: false
}).done(function (html) {
$tabPane.html(html);
}).fail(function (err) {
alert("AJAX error in request: " + JSON.stringify(err, null, 2));
}).always(function () {
$tabPane.removeClass("loader")
});
}
All good so far. My page loads, my tab contents are rendered, and when I click the different tabs, the relevant content is shown.
Now, rather than loading all content at the start, I want to load tab content just-in-time by using the 'shown' event of the tabs. To test this, I've wanted to just make sure I could get a javascript alert when the tab was shown. So, I create the following to trigger the attachment of tab shown events:
$(function () {
attachTabShownEvents();
})
which calls:
function attachTabShownEvents() {
$(document).on('shown', 'a[data-toggle="tab"]', function (e) {
alert('TAB CHANGED');
})
}
I'd therefore expect so see the "TAB CHANGED" alert after the change of tab. But ... I see no alerts.
Could anybody help me out here?
The correct event binding for tab change is shown.bs.tab.
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
alert('TAB CHANGED');
})
Update 11-01-2020 --- Bootstrap 4.5
This is still the correct answer however, this is a bit of additional helpful information found all the way at the bottom of the official bootstrap docs page at: https://getbootstrap.com/docs/4.5/components/navs/#tabs
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
e.target // newly activated tab
e.relatedTarget // previous active tab
})
You can determine which tab has been selected each time the code fires with e.target.
If you have unique IDs on your elements then you could do something like the following so code only runs when the appropriate tab is clicked.
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
switch (e.target.id){
case "mainTab":{
doMainTabStuff();
break;
}
case "configTab":{
doConfigTabStuff();
break;
}
}
})
<a data-toggle="tab" href="#some_special_tab_anchor">
<div id="some_special_tab_anchor" class="tab-pane fade">
special tab content
</div>
$( 'a[data-toggle="tab"]' ).on( 'shown.bs.tab', function( evt ) {
var anchor = $( evt.target ).attr( 'href' );
alert("TAB SHOWN = "+anchor);
// take action based on what tab was shown
if(anchor === "some_special_tab_anchor"){
// do my special thing :)
}
});
Use my Nuget package for lazyloading bootstrap tabs here, its very simple,
just add "lazyload" class to the "ul" element of bootstrap tabs, then add "data-url" equal to url to load to the any tabs anchor element (a). thats it.
https://www.nuget.org/packages/MT.BootstrapTabsLazyLoader.js/
'show' and 'shown' events didn't work for me. My solution is not exactly specifically OP's situation, but the general concepts are there.
I had the same issue with bootstrap forcing its own onclick events
on tabs (menu buttons and content panels). I wanted to lazy load stuff into a panel depending on what menu button was clicked, and some buttons show a panel on the current page, others were to load a page into an iframe.
At first, I stuffed data into a hidden form field tag, which was the same issue. The trick is to detect some sort of change and act on that. I solved the problem by forcing a change and using an alternate event listening on the buttons without having to touch bootstrap.
1) stash iframe target in button as data attribute:
$('#btn_for_iframe').attr('data-url',iframeurl);
2) bind alternate event onto fire off thingy,
and inside, swap out the iframe source
$('#btn_for_iframe').on('mouseup',function(){
console.log(this+' was activated');
$('#iframe').attr('src',$('#btn_for_iframe').attr('data-url'));
});
3) force 'change' event on panel shows, then load iframe src
$('#iframe_panel_wrapper').show().trigger('change');
or you can put the change trigger in the mouseup above.
$(document).ready(function(){
$(".nav-tabs a").click(function(){
$(this).tab('show');
});
$('.nav-tabs a').on('shown.bs.tab', function(event){
alert('tab shown');
});
});

How to execute .click() code when previous click binding finishes

I am trying to use a Twitter Bootstrap button group with data-toggle="buttons-radio" in my site. Bootstrap markup as follows.
<div class="btn-group program-status" data-toggle="buttons-radio">
<button class="btn">All</button>
<button class="btn">Active</button>
<button class="btn">Planning</button>
<button class="btn">End of Life</button>
<button class="btn">Cancelled</button>
</div>
I need to redirect to the same page with query depending on the pressed button. I tried to use following jQuery code to achieve this.
<script>
var sParamStr = '';
function addToParamStr(str) {
sParamStr += str;
}
function redirectToUpdatedLocation() {
$('.program-status > .btn.active').each(function () {
addToParamStr( '?status=' + $(this).text());
});
console.log(sParamStr);
window.location.href = "program" + sParamStr;
}
$document.ready(function () {
$('.program-status > .btn').on('click', function (e) {
redirectToUpdatedLocation();
});
});
</script>
But the browser always redirects to {site}/program without the query string. By commenting out window.location.href = "program" + sParamStr; line, I managed to observe that second click onwards, sParamStr getting appended properly.
It seems that, my code tries to read the text of the pressed button before, .button('toggle') method form bootstrap.js finished. Code worked as intended when I changed function as follows.
$document.ready(function () {
$( '.program-status > .btn').on('click', function (e) {
$(this).addClass('active');
redirectToUpdatedLocation();
});
});
While this method works for me right now, I would like to know the proper way to achieve this. i.e How to execute my code after previous click binding finishes?
UPDATE:
I found this link in the Twitter Bootstrap forum. Seems it is a known issue.
https://github.com/twitter/bootstrap/issues/2380
I'm not sure what Bootstrap's .toggle is doing exactly, but it seems like it does some sort of animation that completes with the setting of the active class. You can try enqueing your code instead:
$( '.program-status > .btn').on('click', function (e){
$(this).queue(function (next) {
redirectToUpdatedLocation();
next();
});
});
For example, click the div as it is being toggled: http://jsfiddle.net/9HwYy/
It also seems a bit silly to me to update every href instead of just the one you clicked on since you are changing the window location anyway.
try
$('.program-status > .btn.active').each(function(i,v){
v = $(v);
addToParamStr( '?status=' + v.text());
});
since im not sure "this" is working in your case.

Jquery UI dialog does not disappear

I am using jquery-ui tabs and dialog functionality.
Each tab has a button on the page which opens a dialog. This works for one of the tabs. However if I go the second tab, the button does not work there. When I come back to the first tab, the dialog does show up but the problem is I notice as I make switches back and forth to the first tab, it keeps on inserting new div's while the old div's have display:none set on them.
I am doing this using JSP. This is how the reusable jsp looks like:
<script>
$(function() {
var formData = null;
$.ajax({
url : "addFormGenerator.html",
success : function(data) {
formData = data;
$("#addFormDialog").html(data);
$("#addFormDialog").dialog({
autoOpen : false,
height : 300,
width : 350,
modal : true,
buttons : {
"Add" : function() {
$(this).dialog("close");
},
Cancel : function() {
$(this).dialog("close");
}
},
close : function() {
}
});
}
});
$("#addButton").button().click(function() {
$("#addFormDialog").html(formData);
$("#addFormDialog").dialog("open");
});
});
</script>
<button id="addButton">Click here to Add New</button>
<div id="addFormDialog" title="Add New"></div>
This jsp fragment is included in other jsp pages as well.
I was assuming as I switch between tabs the old button will be garbage collected.
Can you help me understand the problem and fix it?
You need not render the following part from your jsp's response
<div class="addFormDialog" title="Add New"></div>
$("#addButton").button().click(function() {
$("#addFormDialog").html(formData);
$("#addFormDialog").dialog("open");
});
Just have the following, ideally with class names and not duplicate id's
<button class="addButton">Click here to Add New</button>
UPDATE:
I still don't think you need unique id's -
<div id="tabs-container">
<!-- tabs here -- >
<-- let's say this is tab#1 -->
<button class="addButton">Click here to Add New</button>
<div class="addFormDialog" title="Add New"></div>
<!-- tab1 -->
</div>
$('#tabs-container').on('click' , '.addButton', function(){
var dialogContent = $(this).siblings('.addFormDialog');
//now call .dialog({..}); or whatever you need
});
This way you're binding just one click handler that listens to any click that bubbles up from a .addButton and then searches for its sibling .addFormDialog. (I hope I'm not sounding too confusing)

Categories