Reputation: 14794
If I create a modal inline with buttons...I want to be able to perform a certain action when each is clicked. However, I am unable to grab hold of these buttons generated in the modal.
Does anyone know how I can grab these?
$('.open-popup-link').magnificPopup({
items: {
type: 'inline',
src: $('<div class="white-popup">\
<h4>Are you sure you were discharged for failing a drugs test?</h4>\
<p>You will not be able to change your answer once you have submitted these details.</p>\
<button id="test-popup-no">No, I\'ve made a mistake</button>\
<button id="test-popup-yes">Yes, I\'m sure</button>\
</div>')
},
type: 'inline',
midClick: true
});
I'd like to perform different actions when each of the buttons is clicked depending on its ID.
Please help if you can. I've been struggling with this. Just doing a standard jQuery selection does not seem to work.
Thanks, Michael.
Upvotes: 2
Views: 2171
Reputation: 4626
The code posted by @Irvin is valid, but not very good in terms of app performance. I'd recommend to use open/close callbacks to bind/unbind click events, e.g.:
$('.open-popup-link').magnificPopup({
items: {
type: 'inline',
src: $('<div class="white-popup">\
<h4>Are you sure you were discharged for failing a drugs test?</h4>\
<p>You will not be able to change your answer once you have submitted these details.</p>\
<button id="test-popup-no">No, I\'ve made a mistake</button>\
<button id="test-popup-yes">Yes, I\'m sure</button>\
</div>')
},
type: 'inline',
midClick: true,
callbacks: {
open: function() {
this.content.on('click.mycustomevent', '#test-popup-no', function() {
alert('hello world');
});
},
close: function() {
this.content.off('click.mycustomevent');
}
}
});
Upvotes: 4
Reputation: 30993
You can try binding a click handler using event delegation with jQuery on
:
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
Code:
$('.open-popup-link').magnificPopup({
items: {
type: 'inline',
src: $('<div class="white-popup">\
<h4>Are you sure you were discharged for failing a drugs test?</h4>\
<p>You will not be able to change your answer once you have submitted these details.</p>\
<button id="test-popup-no">No, I\'ve made a mistake</button>\
<button id="test-popup-yes">Yes, I\'m sure</button>\
</div>')
},
type: 'inline',
midClick: true
});
$('body').on('click','#test-popup-no', function(){
alert('Nope!');
})
$('body').on('click','#test-popup-yes', function(){
alert('Yes');
})
Demo: http://jsfiddle.net/IrvinDominin/A9dQ7/
Upvotes: 2