How to popup javascript modal with code instead of button click - javascript

I have the following modal:
<div class="modal fade" id="m_modal_1" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
I have the following button that pops up the modal:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#m_modal_1"> Launch Modal</button>
Instead of initiating from the button, how do I popup from code? I was thinking something like this:
if(status == 1){
modal("show");
}

Assuming that you're using Bootstrap (based on the classes).
You can use the following:
$('#m_modal_1').modal('show')

You need to add eventlistener to any element, so once the event is triggered you change classes of the modal element or style.
Assuming you have some element (ie button with classname btn and modal with classname modal)
document.querySelector('.btn').addEventListener('click', () => {
document.querySelector('.modal').classList.toggle('hidden');
}
And your css can be like this
.hidden {
display: none;
// or
opacity: 0;
}

I think you are using bootstrap.
so in your case
if(status == 1){
$("#m_modal_1").modal("show");
}
"show" is a option of modal function.
See more option and usage here
https://getbootstrap.com/docs/4.0/components/modal/#options

Basically it depends on when you want to popup your modal.suppose you want to popup on page
ready then,
$(document).ready(function(e){
$(#modal_id).show();
});

Related

Modal disappearing instantly

I am a beginner, trying to implement 'click' event listener to pop up a modal. But as soon as I click the link the modal appears and disappear instantly.
const btn = document.getElementById(btn");
const modal= document.getElementById("modal");
const showModal = function (el, modalId) {
el.addEventListener("click", function () {
modalId.classList.remove("hidden");
});
};
showModal(btn, modal);
.hidden{
display: none
}
<a class='btn'> Click </a>
<div id='modal' class='hidden'> Modal Content </div>
you should define id="btn" on your a tag to be able to do
document.getElementById("btn")
const btn = document.getElementById("btn");
const modal = document.getElementById("modal");
const showModal = function(el, modalId) {
el.addEventListener("click", function() {
modalId.classList.remove("hidden");
});
};
showModal(btn, modal);
.hidden {
display: none
}
<a id="btn"> Click </a>
<div id='modal' class='hidden'> Modal Content </div>
Thanks You so much guys for responding. I found my mistake, I was using 'link' tag with empty 'href' attribute, due to which the page was reloading ever time I clicked it. I simply replaced the links with button tag and now it is working just fine.
Although I still want to know if it is possible to stop the page from reloading when link element is clicked.
Also, thank you for highlighting the 'class/id' typo.

Why does bootstrap modal activation work after page refresh but not after initial form push?

I am pushing a form to our users. The form has a button that is intended to open a bootstrap multi-step-modal. When I push the form this button does not open the modal, but if I refresh the page, then it works as intended.
I have tried having the button manually open the modal with jquery, but that breaks other functionality of the modal.
Here is the definition of the button and the modal.
<input type="button" class="btn btn-primary" data-toggle="modal" data-backdrop="false" data-target="#demo-modal-3" value ="Create"/>
<div class="modal multi-step" style="color:black;" id="demo-modal-3">
I am performing a minimum of additional javascript beyond the default behavior.
$.getScript("/files/bootstrap.min.js", function() {
$.getScript("/files/multi-step-modal.js", function() {
sendEvent = function(sel, step) {
$(sel).trigger('next.m.' + step);
}
$('#demo-modal-3').on('hidden.bs.modal', function () {
//reset();
console.log('modal reset');
$('#demo-modal-3').trigger('next.m.1');
$('#demo-modal-3').find('.step-1').show();
});
});
});
When the button functions properly, I can see the div is modified to display the modal.
<div class="modal multi-step in" style="color: black; display: block;" id="demo-modal-3">
However when it is not working, the div is also modified, but display is set to 'none' and the modal does not appear.
<div class="modal multi-step" style="color: black; display: none;" id="demo-modal-3">

JavaScript: How to get height of image after change the src

HTML:
<div class="modal fade" data-backdrop="static" role="dialog">
<div class="modal-dialog" role="document">
<img/>
</div>
</div>
JS:
$(".btn").click(function() {
$(".modal img").prop("src", "new src");
alert($(".modal img").height());
$(".modal").modal("show");
});
Alert: 0
Hello, I am trying get height of image after change the src.
i have a image in the bootstrap modal, after click the button change src of the image and show the modal .
I can not get correct height of image, because the image wont loaded src until modal is visible, So any way to force the src to load, or any way to get the correct height.BTW i tried onload and load, both not work.
Try this: https://jsfiddle.net/yyma7fkj/
$(".btn").click(function() {
$(".modal img").load(function() {
alert("height:" + this.height + " width:" + this.width);
$(".modal").modal("show");
}).prop("src", "http://jsfiddle.net/img/logo.png");
});

if same class, fadeIn / fadout

I have a setup here in jsFiddle: http://jsfiddle.net/2PmnQ/
I'm trying to make a function that will check if the modal has the same class as the button so the button will bring up the modal with the same class. I'm obviously trying to do this dynamically all within one function rather than doing a if statement for every class.
var p = $(".popUp");
var position = p.position();
var tagLength = $("p a").width();
$( ".modal" ).css({left: (position.left + tagLength + 10) + "px", top: position.top + "px"});
$( ".popUp").hover(
function() {
$( ".modal" ).stop().fadeIn();
}, function() {
$( ".modal" ).stop().fadeOut();
}
);
I would use a custom data attribute instead of a class to save the target class:
<p class="popUp" data-modal="one"><a>popUp one here</a></p>
<p class="popUp" data-modal="two"><a>popUp two here</a></p>
<div class="modal one">PopUp one should be here</div>
<div class="modal two">PopUp two should be here</div>
That way you don't have to filter the target out of the trigger element classes and only need this in your hover function:
$('.popUp').hover(function(){
$('.modal.'+$(this).data('modal')).fadeIn();
},function(){
$('.modal.'+$(this).data('modal')).fadeOut();
});
http://jsfiddle.net/2PmnQ/1/
V2 using jQuery UI position() plugin:
<!-- i switched the popup classes to the `a` here so it works in the fiddle -->
<p><a class="popUp" data-modal="one">popUp one here</a></p>
<p><a class="popUp" data-modal="two">popUp two here</a></p>
<div class="modal one">PopUp one should be here</div>
<div class="modal two">PopUp two should be here</div>
JS:
$('.popUp').hover(function(){
$('.modal.'+$(this).data('modal'))
// reset positions otherwise it doesn't work correctly after the first time. don't know why :(
// looks like this problem: http://forum.jquery.com/topic/position-keeps-adding-original-left-and-top-to-current-values-in-ie-8
.css({'left':0,'top':0})
// position modal 10px to the right of the popup link
.position({'my':'left+10 center',
'at' : 'right center',
'of' : $(this)
}
).fadeIn();
},function(){
$('.modal.'+$(this).data('modal')).fadeOut();
});
http://jsfiddle.net/2PmnQ/10/
(Be sure to include the jQuery UI with at least the position plugin: http://jqueryui.com/download/#!version=1.11.0&components=0001000000000000000000000000000000000. Yeah maybe it's a bit overkill for this but it's really convenient)

Twitter Bootstrap Modal Event Not Fired When Modal is Shown

According to the docs:
http://getbootstrap.com/javascript/#modals
It should fire the methods "show.bs.dropdown" and "shown.bs.dropdown". But it doesn't:
http://jsfiddle.net/mQunq/3/
HTML:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">Hello world</div>
</div>
</div>
jQuery:
// show.bs.modal doesn't work either
$('#myModal')
.modal('show')
.on('show.bs.modal', function() {
alert('shown baby!');
});
Youe need first register event then trigger it
$('#myModal')
.on('show.bs.modal', function() {
alert('shown baby!');
}).modal('show');
jsfiddle
When it happens
Event shown.bs.modal is not fired when modal has also class "fade". Whereas show.bs.modal always works.
See https://github.com/twbs/bootstrap/issues/11793
HTML:
<div class="modal fade" id="first" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">Hello world from first modal</div>
</div>
</div>
<div class="modal" id="second" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">Hello world from second modal</div>
</div>
</div>
jQuery:
$('.modal').on('shown.bs.modal', function() {
//fired only in second modal
console.info('shown.bs.modal');
});
$('.modal').on('show.bs.modal', function() {
//fired always
console.info('show.bs.modal');
});
Solution
For bootstrap v3.3.6 replace line 1010 with:
that.$element // wait for modal to slide in
What is the problem
Look at lines 1006-1015:
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
Without transition (no fade class) the event e is triggered right away (on that.$element).
With transition, I'm not sure why exactly, but somehow the bsTransationEnd event from function emulateTransitionEnd is not handled by that.$dialog.one(). But with that.$element, everything seem to work.
Similar thing happened to me and I have solved using setTimeout.
Bootstrap is using the following timeout to complete showing:
c.TRANSITION_DURATION=300,c.BACKDROP_TRANSITION_DURATION=150,
So using more than 300 must work and for me 200 is working:
$('#myModal').on('show.bs.modal', function (e) {
setTimeout(function(){
//Do something if necessary
}, 300);
})
you forgot the "n" on shown
$(document).ready(function(){
$('#myModal')
.modal('show')
.on('shown.bs.modal', function() {
alert('shown baby!');
});
});
Use document instead of your custom selector. Both shown.bs.modal and show.bs.modal work just fine
$(document).on('shown.bs.modal', '.modal', function() {
alert();
});
In case someone stumbles upon this problem, make sure you hook the on hidden / shown event before firing the toggle of the modal. That is, declare this:
$("#selector").on("hidden.bs.modal", function () {
// do the right thing
});
Before calling the toggle of the modal, e.g.:
("#selector").modal("toggle");
I know this is basic, but in a convoluted code it happens.
I found a solution that works with .fade transitions:
$(document).on($.support.transition.end, '.modal.fade.in', function(e) {
var $target = $(e.target);
if ($(e.target).is(".modal-dialog")) {
console.log("Modal Shown")
}
});
$(document).on($.support.transition.end, '.modal.fade', function(e) {
var $target = $(e.target);
if (!$target.is(".modal.fade.in") && !$target.is(".modal-dialog")) {
console.log("Modal Hidden")
}
});
If your modal is dynamically created, select the closest static parent element and add your modal as a parameter for bootstrap modal events to work:
/* body is static, .modal is not */
$("body").on('shown.bs.modal', '.modal', function() {
alert('shown');
});
$("body").on('hidden.bs.modal', '.modal', function() {
alert('hidden');
});
$("body").on('show.bs.modal', '.modal', function() {
alert('show');
});
$("body").on('hide.bs.modal', '.modal', function() {
alert('hide');
});

Categories