Can I check if Bootstrap Modal Shown / Hidden? - javascript

Can I check if Bootstrap Modal currently Shown / Hidden Programatically?
Like bool a = if("#myModal").shown(); ?
I need true/false

alert($('#myModal').hasClass('in'));
It will return true if modal is open

The best method is given in the docs
$('#myModal').on('shown.bs.modal', function () {
// will only come inside after the modal is shown
});
for more info refer http://getbootstrap.com/javascript/#modals

its an old question but anyway heres something i used incase someone was looking for the same thing
if (!$('#myModal').is(':visible')) {
// if modal is not shown/visible then do something
}

All Bootstrap versions:
var isShown = $('.modal').hasClass('in') || $('.modal').hasClass('show')
To just close it independent of state and version:
$('.modal button.close').click()
more info
Bootstrap 3 and before
var isShown = $('.modal').hasClass('in')
Bootstrap 4
var isShown = $('.modal').hasClass('show')

When modal hide? we check like this :
$('.yourmodal').on('hidden.bs.modal', function () {
// do something here
})

Use hasClass('in'). It will return true if modal is in OPEN state.
E.g:
if($('.modal').hasClass('in')){
//Do something here
}

In offical way:
> ($("element").data('bs.modal') || {})._isShown // Bootstrap 4
> ($("element").data('bs.modal') || {}).isShown // Bootstrap <= 3
{} is used to avoid the case that modal is not opened yet (it return undefined). You can also assign it equal {isShown: false} to keep it's more make sense.

Here's some custom code that gives the modal states more explicitly named classes:
$('.modal').on('show.bs.modal', function(e)
{
e.currentTarget.classList.add("modal-fading-in");
e.currentTarget.classList.remove("modal-fading-out");
e.currentTarget.classList.remove("modal-hidden");
e.currentTarget.classList.remove("modal-visible");
});
$('.modal').on('hide.bs.modal', function(e)
{
e.currentTarget.classList.add("modal-fading-out");
e.currentTarget.classList.remove("modal-fading-in");
e.currentTarget.classList.remove("modal-hidden");
e.currentTarget.classList.remove("modal-visible");
});
$('.modal').on('hidden.bs.modal', function(e)
{
e.currentTarget.classList.add("modal-hidden");
e.currentTarget.classList.remove("modal-fading-in");
e.currentTarget.classList.remove("modal-fading-out");
e.currentTarget.classList.remove("modal-visible");
});
$('.modal').on('shown.bs.modal', function(e)
{
e.currentTarget.classList.add("modal-visible");
e.currentTarget.classList.remove("modal-fading-in");
e.currentTarget.classList.remove("modal-fading-out");
e.currentTarget.classList.remove("modal-hidden");
});
You can then easily target the modal's various states with both JS and CSS.
JS example:
if (document.getElementById('myModal').hasClass('modal-fading-in'))
{
console.log("The modal is currently fading in. Please wait.");
}
CSS example:
.modal-fading-out, .modal-hidden
{
opacity: 0.5;
}

With Bootstrap 4:
if ($('#myModal').hasClass('show')) {
alert("Modal is visible")
}

if($('.modal').hasClass('in')) {
alert($('.modal .in').attr('id')); //ID of the opened modal
} else {
alert("No pop-up opened");
}

For me this works
if($("#myModal").css("display") !='none' && $("#myModal").css("visibility") != 'hidden')
alert("modal shown");

I try like this with function then calling if needed a this function. Has been worked for me.
function modal_fix() {
var a = $(".modal"),
b = $("body");
a.on("shown.bs.modal", function () {
b.hasClass("modal-open") || b.addClass("modal-open");
});
}

This resolved your problems, if true no refresh, and false refresh
var truFalse = $('body').hasClass('modal-open');

Related

Javascript ignoring if statements

I'm somewhat new to Javascript. I'm trying to make it so that clicking on an image on one page takes you to a new page and shows a specific div on that new page, so I used sessionStorage to remember and booleans to keep track of which image is being clicked. Right now, the code always executes the first if statement, regardless of which image is clicked. This code works fine in normal java so I can't figure out why my if statements are being ignored in javascript. I also tried adding an 'else' at the end, and tried ===. Here's my javscript, and thank you!
sessionStorage.clickedLeft;
sessionStorage.clickedMiddle;
sessionStorage.clickedRight;
function openedProjectFromGallery() {
if(sessionStorage.clickedLeft) {
$(".left-project-pop-up").show();
} else if (sessionStorage.clickedMiddle) {
$(".middle-project-pop-up").show();
} else if (sessionStorage.clickedRight) {
$(".right-project-pop-up").show();
}
sessionStorage.clickedLeft = false;
sessionStorage.clickedMiddle = false;
sessionStorage.clickedRight = false;
}
$("document").ready(function () {
$(".pop-up .x-button").click(function(){
$(".pop-up").hide();
});
$(".project-description .x-button").click(function(){
$(".project-pop-up").hide();
});
$(".left-project-thumb img").on("click", ".left-project-thumb img", function(){
sessionStorage.clickedLeft = true;
sessionStorage.clickedMiddle = false;
sessionStorage.clickedRight = false;
openedProjectFromGallery();
});
$(".profile-left-project img").click(function(){
$(".left-project-pop-up").show(1000);
});
$(".middle-project-thumb img").on("click", ".middle-project-thumb img", (function(){
sessionStorage.clickedMiddle = true;
sessionStorage.clickedLeft = false;
sessionStorage.clickedRight = false;
openedProjectFromGallery();
});
$(".profile-middle-project img").click(function(){
$(".middle-project-pop-up").show(1000);
});
$(".right-project-thumb img").on("click", ".right-project-thumb img", (function(){
sessionStorage.clickedRight = true;
sessionStorage.clickedLeft = false;
sessionStorage.clickedMiddle = false;
openedProjectFromGallery();
});
$(".profile-right-project img").click(function(){
$(".right-project-pop-up").show(1000);
});
});
You are defining function openedProjectFromGallery() with in document.ready . Define it outside document.ready and also give your three booleans some initial value at the top of your code if not initialized with some value or they are empty. I hope this would help.
It is not really answer to your orginal question,as the main issue with your code is, as #njzk2 says, that openProjectFromGallery only being called once, and not on each event, however I wanted to put my two coins on how this code could look like.
This is good example where custom events should be used
$(document).on('showPopup', function( e, popup ) {
$('.'+popup + '-project-pop-up').show()
})
$(document).on('hidePopup', function( e ) {
$('.popup').hide()
})
$('.left-project-thumb img').on('click', function(e) {
$(document).trigger('showPopup', ['left'])
})
$('.right-project-thumb img').on('click', function(e) {
$(document).trigger('showPopup', ['right'])
})
I think you get an idea.
On the other hand, it always nice to use event delegation with a lot of similar events as well as dom data.
<div class='popup' data-popup='left'>
<img />
</div>
$(document).on('click','.popup', function( e ) {
$(document).trigger('showPopup', [$(this).data('popup')])
})
From what I can see openedProjectFromGallery is only getting called on document load.
Add a call to it into each of the event handling functions or use jQuery's delegate function to assign event handling to each image.

Fill twitter button with dynamic content

is it possible to create a twitter-button , while clicking a link? :
http://fiddle.jshell.net/gmq39/22/
I tried with:
$.getScript('http://platform.twitter.com/widgets.js');
The "button", which appear´s has no functionlaity and style´s
Anybody know´s a workaround or what do i need to inlcude? need your help.. greetings!!
Use twttr.widgets.load(); to bind the twitter functionality to a dynamically added button.
Also, to make sure you don't load the script over and over again, you could first check if the script is already loaded with something like this
function twitter() {
if ($(".twitter-follow-button").length > 0) {
if (typeof (twttr) != 'undefined') {
twttr.widgets.load();
} else {
$.getScript('http://platform.twitter.com/widgets.js');
}
}
}
$(function () {
$('body').html('Follow #MagnusEngdal')
twitter();
});
http://jsfiddle.net/23D8C/1/

Redefining a jQuery dialog button

In our application we use a general function to create jQuery dialogs which contain module-specific content. The custom dialog consists of 3 buttons (Cancel, Save, Apply). Apply does the same as Save but also closes the dialog.
Many modules are still using a custom post instead of an ajax-post. For this reason I'm looking to overwrite/redefine the buttons which are on a specific dialog.
So far I've got the buttons, but I'm unable to do something with them. Is it possible to get the buttons from a dialog (yes, I know) but apply a different function to them?
My code so far:
function OverrideDialogButtonCallbacks(sDialogInstance) {
oButtons = $( '#dialog' ).dialog( 'option', 'buttons' );
console.log(oButtons); // logs the buttons correctly
if(sDialogInstance == 'TestInstance') {
oButtons.Save = function() {
alert('A new callback has been assigned.');
// code for ajax-post will come here.
}
}
}
$('#dialog').dialog({
'buttons' : {
'Save' : {
id:"btn-save", // provide the id, if you want to apply a callback based on id selector
click: function() {
//
},
},
}
});
Did you try this? to override button's callback based on the need.
No need to re-assign at all. Try this.
function OverrideDialogButtonCallbacks(dialogSelector) {
var button = $(dialogSelector + " ~ .ui-dialog-buttonpane")
.find("button:contains('Save')");
button.unbind("click").on("click", function() {
alert("save overriden!");
});
}
Call it like OverrideDialogButtonCallbacks("#dialog");
Working fiddle: http://jsfiddle.net/codovations/yzfVT/
You can get the buttons using $(..).dialog('option', 'buttons'). This returns an array of objects that you can then rewire by searching through them and adjusting the click event:
// Rewire the callback for the first button
var buttons = $('#dialog').dialog('option', 'buttons');
buttons[0].click = function() { alert('Click rewired!'); };
See this fiddle for an example: http://jsfiddle.net/z4TTH/2/
If necessary, you can check the text of the button using button[i].text.
UPDATE:
The buttons option can be one of two forms, one is an array as described above, the other is an object where each property is the name of the button. To rewire the click event in this instance it's necessary to update the buttons option in the dialog:
// Rewire the callback for the OK button
var buttons = $('#dialog').dialog('option', 'buttons');
buttons.Ok = function() { alert('Click rewired!'); };
$('#dialog').dialog('option', 'buttons', buttons);
See this fiddle: http://jsfiddle.net/z4TTH/3/
Can you try binding your new function code with Click event of Save?
if(sDialogInstance == 'TestInstance') {
$('#'+savebtn_id).click(function() {
alert('A new callback has been assigned.');
// code for ajax-post will come here.
});
}

jquery simple modal help on window load

I'm trying to something like this if in the html there is a div called "#super" load it in the simple modal if not do nothing. I managed to do this with the my skill :D which is none: to load the modal if the #super exists, but it still loads doesn't matter if it exitst or not. PLease help I'm absolute noob on jquery.
if( $('super') ){ $("#super").modal({onOpen: function (dialog) {
dialog.overlay.fadeIn('slow', function () {
dialog.container.slideDown('slow', function () {
dialog.data.fadeIn('slow');
});
});
}});
I'm using this jquery plugin link text
If #super does not exist, nothing will happen. So, the following should fit your needs:
$("#super").modal({onOpen: function (dialog) {
dialog.overlay.fadeIn('slow', function () {
dialog.container.slideDown('slow', function () {
dialog.data.fadeIn('slow');
});
});
});
I'm not quite sure what it is that you want to do, in the if/else conditions, but to test for the existence of something:
if ($('#super').length) {
// it exists, do stuff
}
else {
// it doesn't exist, do other stuff. Or nothing
}
I'm sorry I can't be more specific, but I've not worked with the dialog/modal plugin.
The problem is this check
if( $('#super') )
will always return true, since the jQuery function always return a jQuery object which is not a false value.
Instead try this
if( $('#super').length > 0 )

whats wrong with this jquery

I'm getting syntax error in firebug here is the code :
$('#moderator-attention').live('toogle', function(){
function () {
$(".moderator-tex").show();
},
function () {
$(".moderator-tex").hide();
}
});
I want to create a toogle function, when button is clicked then textarea with class moderator-tex should appear .. and if other button is clicked then should be hidden ..
Here's the solution: http://api.jquery.com/live/#multiple-events
And the syntax error occurs because you have something like this:
function() {
function() {
},
function() {
}
}
And this makes no sense.
Based on your question/comments maybe you ought to try this :
$("input:radio").click(function() {
var value = $this("attr", "value");
if(value == "expected value"){
$(".moderator-tex").show();
}else{
$(".moderator-tex").hide();
}
});
You should set some value for this particular radio button to make this work
Try this:
$('#moderator-attention').live('toogle', function(){
$(".moderator-tex").slideToggle();
}
});
If your textarea is not created on-the-fly, you can even try:
$('#moderator-attention').click(function(){
$(".moderator-tex").slideToggle();
});
$('#moderator-attention').live('toogle', function () {
$('.moderator-text').toggle();
});
Would be how I would do it.
Not quite sure what you're trying to achieve doing it your way...

Categories