JQueryUI how to 'self' close a dialog - javascript

I'm working on a web app that uses jQueryUI and creates a ton of dialogs. The dialogs are all different, and the button to close the dialog can end up embedded several div's into the dialog.
I'd like a function that always closes the containing dialog.
Take for example the following html:
<div id="demoDialog">
<div>
<div id='demoDialogSubmit'>
<input type='submit' onClick='selfCloseDialog();' value='Ok' style='margin-top:10px' />
</div>
<div>
<div>
Somewhere in my js code I initialized this as a dialog:
$( "#demoDialog" ).dialog( params );
Now for the on-click I have a few not so great choices. I could insist on the close button knowing the id of the dialog. E.g. do something like:
onclick="$( '#demoDialog' ).dialog( 'close' );"
But I'd rather have generic code instead of always having to carry around the id of the dialog so I can send it to a widget that may close it.
Or I can remember how many layers down I am:
function selfCloseDialog() { $(this).parent().dialog( 'close' ); }
But really I want selfCloseDialog() to just hunt up the layers of elements looking for the dialog object to close. How do I do this?
#Update:
So i got it working. Thanks everyone for their suggestions the problem actually had two issues.
First one problem was here:
<input type='submit' onClick='selfCloseDialog();' value='Ok'/>
It should be:
<input type='submit' onClick='selfCloseDialog(this);' value='Ok'/>
The button element is not passed in as the "this" argument to the function. Which seems obvious now.
And the following direct method JAAulde below works and seems the cleanest:
function selfCloseDialog( caller ) {
$(caller).closest( ".ui-dialog-content" ).dialog('close');
}
There were several answers involving closest and a selector- but I don't see any reason to use anything except the plain class selector he suggests.

When making your dialog, include a close button:
var params = {
//whatever you already had in there
buttons: {
// In the buttons object, the "key" will be the button text, the function
// will be executed on click of the button in scope of the dialoged element
Close: function () {
$(this).dialog('close');
}
}
};
$( "#demoDialog" ).dialog( params );
And from code running in scope of ANY descendant element of the dialoged element, run:
$(this).closest('.ui-dialog-content').dialog('close');

Not sure if I'm exactly understanding what you're asking, but it seems the easiest way would be to add a standard class to all your dialogs, and then have code like:
$(this).closest('.dialog-class').dialog('close');
closest() is defined here:
http://api.jquery.com/closest/

*updated to reflect the ajax part of the dialog. *updated to reflect comments
<div id="soemthing.random.ui.dialog.makes">
.... your content....
<a class='custom-close' href="#Close">Custom Close</a>
....
</div>
$(function(){
$("your selector").dialog();
var selector = ":ui-dialog";
//developers choice. ".ui-dialog-content" is faster, ":ui-dialog" is guaranteed
$(selector ).on({
"click":function(event){
event.preventDefault();
$(this).closest(selector).dialog("close");
}
},"a.custom-close",null);
})

I'd suggest using a class instead of writing inline function calls, but that's up to you.
Here's my hackish solution with event delegation where clicking an element with the selfclose class will close the ancestor dialog:
$(document).on('click', '.selfclose', function() {
$(this).parents().each(function() {
try {
$(this).dialog('close');
} catch(e) {}
});
});
Fiddle
But as DefyGravity mentioned, using the :ui-dialog selector is a much cleaner solution:
$(document).on('click', '.selfclose', function() {
$(this).closest(":ui-dialog").dialog("close");
});
Fiddle

check this:
http://jsfiddle.net/Wqh4Y/3/
function closeParentDialog(closeButton)
{
closeButton.parents('.ui-dialog').eq(0).find('a.ui-dialog-titlebar-close').eq(0).click();
}
$(function() {
$( "#dialog" ).dialog();
});​
you can use it like this:
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.
<span> <a class="close-dialog" onclick="closeParentDialog($(this))">selfclose</a> </span>
</p>
</div>

Related

How to load a specific div/class in a file using ajax?

I have a file called main.html that contains several div's each with 2 classes:
1st is their specific class 2nd is a class called menu-item which I use to determine if an event will triggered when clicked.
The file contains this:
<div id="load-here">
</div>
<div class="item-1 menu-item">
click this
</div>
I also have a gallery.html file which I want to be loaded into the main.html file in the #load-here div, and let's say it contains this:
<div class="menu-item>
<!-- some image here -->
<img href="img/1.jpg />
</div>
The script I have is this:
$(document).ready(function() {
$( "div" ).click(function() {
if ( $( this ).hasClass( "menu-item" ) ) {
$("#load-here").load("gallery.html" + this.class);
}
});
});
The problem: It's not working. I've tried various changes. Somehow it's not loading into the #load-here div
Take a look at this: http://api.jquery.com/load/
$( "#b" ).load( "article.html #target" );
There seem to several issues:
By this: $( "div" ).click(function() ... you are registering the click on all divs available. This might cause strange behaviour. Better use: $("div.menu-item").click( ...
Make sure you understand the context and the event target in your callback function. Sometimes this is cheating you, as the context of the call may be different. Things are more clear if you handle the event as explicit parameter and check the event target.
I guess you would like to give a parameter for your gallery.html, but as #charlietfl mentions, there is no .class. But, in the DOM there is a .className. Better try to use the jQuery $().attr('class'). Also, the parameter needs a separator: gallery.html?parameter
To sum it up, here my suggestion:
$("div.menu-item").click( function(event) {
var jqTarget = $(event.target).closest('.menu-item');
if ( jqTarget.hasClass( "menu-item" ) ) {
$("#load-here").load("gallery.html" + "?" + this.class);
}
});
closest() will attempt to find the closest matching element, in case the click target was not on the div itself, but rather a child img or else. So, the condition in the suggestion should be used to find out about more specific about which menu item was clicked: if ( jqTarget.hasClass( "that-specific-item" ) ...

jQuery .click() not working (debugging)

I am new to jQuery and am making a few .click() functions for my website, but no matter what I try, I can't get them to work.
jquery:
$(document).ready(function(){
$("#underlay-img-container-btns-add").click(function(){$("#underlay-img-container-form-file").click();});
$("#underlay-img-container-btns-submit").click(function(){document.forms['underlay-img-container-form'].submit();$("#underlay-img-container-general_loader").css("display","inline-block");});
$("#underlay-img-container-form-file").change(function(){readURLImg(this);});
$("#underlay-gif-container-btns-add").click(function(){$("#underlay-gif-container-form-file").click();});
$("#underlay-gif-container-btns-submit").click(function(){document.forms['underlay-gif-container-form'].submit();$("#underlay-gif-container-general_loader").css("display","inline-block");});
$("#underlay-gif-container-form-file").change(function(){readURLImg(this);});
});
readURLImg (displays an image preview before submission. This is part of a file uploading script.):
function readURLImg(input){if(input.files&&input.files[0]){var reader=new FileReader();reader.onload=function(e){$("#underlay-img-container-preview").attr("style","background-image:url("+e.target.result+");color:#fafafa");}
reader.readAsDataURL(input.files[0]);}}
I am sure my ids are correct. I have been trying to find the answer for hours with no success.
i have checked your website
then I've clicked on button upload you picture > opened the terminal and test
$("#underlay-img-container-btns-add").click(function(){alert('btn clicked')})
and the results appears
So, your problem is to call the events when the popups are ready
to Understand the concept
close the popup and try the same code it will retrieve empty array '[]'
<div class="btn" id="green" >
<div class="icon-image"></div>
<span>Upload your picture</span>
</div>
and add
$('.btn#green').click(function() {
$('.overlay').html($('.overlay').html().replace(/!non_select_tag!/g, 'img'));
$('.overlay').html($('.overlay').html().replace(/!non_select_txt!/g, 'Picture'));
// add you events
$("#underlay-img-container-btns-add").click(function(){alert('btn clicked')})
$('.overlay').show();
})
this will work
try
$("#underlay-img-container-btns-add").on( 'click', function () { ... });
may not work because content is dynamically created.
try
$("#underlay-img-container-btns-add").bind( 'click', function () { ... });
To bind events to dynamically generated elements in DOM, you may use
$('document').on( 'click', '#selector', function () {
...
});
This binds event to the DOM rather than to the element directly, which may not exist all the time.
try
$("body").delegate("#underlay-img-container-btns-add",'click',function(){
....
});

.click function not working when the event is called by element created by another function

I have this function that create an element
function AddPayment(ID)
{
showForm = $('#AddPaymentForm').html();
$('#divAJAX_'+ID).html(showForm);
$(".cancel").click(function(){ AddPayment(ID); });
}
Coming from this
<div id='AddPaymentForm'>
<span class='button' id='cancel' class='cancel' >Cancel</span>
</div>
I wanted that function to place the element in here
<div id='divAJAX_ID'></div>
I also wanted that function to create an onclick function on my span, but it isn't working.
I guess the problem is coming from placing the
$(".cancel").click(function(){ AddPayment(ID); });
at the wrong placement. I've tried all the possible place but I can't still work this right.
What's wrong?
You have two class attributes on the same element. It should be something like:
class="button cancel"
instead of
class="button" id="whatever" class="cancel"
It is probably causing trouble to jQuery.
See how it start working on this fiddle: http://jsfiddle.net/pvNrg/2/
First, your question as the html:
<div id='AddPaymentForm'>
<p>Coming from this</p>
</div>
<span id='cancel' class='cancel'>Cancel</span>
<p>I wanted that function to place the element in here</p>
<div id='divAJAX_ID'></div>
<p>I also wanted that function to create an onclick function on my span, but it isn't working. I guess the problem is coming from placing the ... at the wrong placement. I've tried all the possible place but I can't still work this right.</p>
<p>What's wrong?</p>
And the javascript:
$(function () {
function AddPayment(ID) {
showForm = $('#AddPaymentForm').html();
$('#divAJAX_' + ID).html(showForm);
}
$(".cancel").click(function () {
AddPayment('ID');
});
});
For dynamically created elements ,You have to do event delegation
$(document).on("click", ".cancel" , function(event){
alert($(this).text());
});
Use this code
function AddPayment(ID)
{
var showForm = $('#AddPaymentForm').html();
var container = $('#divAJAX_'+ID);
container.html(showForm);
container.find(".cancel").click(function(){ AddPayment(ID); });
}
$("#AddPaymentForm,[id^=divAJAX_]").on("click", ".cancel" , function(event){
alert($(this).text());
});
Attach the delegated event handlers only the list of containers you need to monitor (not the document) if you need to save performance (you don't need to monitor all the .cancel). With this approach, the event does not have to bubble up more levels. If you have anther element that is parent of AddPaymentForm and all divAJAX_. You could write like this:
$("#anotherContainer").on("click", ".cancel" , function(event){
alert($(this).text());
});

Prevent icon inside disabled button from triggering click?

Trying to figure out proper way to make a click event not fire on the icon of a disabled link. The problem is when you click the Icon, it triggers the click event. I need the selector to include child objects(I think) so that clicking them triggers the event whenever the link is enabled, but it needs to exclude the children when the parent is disabled.
Links get disabled attribute set dynamically AFTER page load. That's why I'm using .on
Demo here:(New link, forgot to set link to disabled)
http://jsfiddle.net/f5Ytj/9/
<div class="container">
<div class="hero-unit">
<h1>Bootstrap jsFiddle Skeleton</h1>
<p>Fork this fiddle to test your Bootstrap stuff.</p>
<p>
<a class="btn" disabled>
<i class="icon-file"></i>
Test
</a>
</p>
</div>
</diV>​
$('.btn').on('click', ':not([disabled])', function () { alert("test"); });​
Update:
I feel like I'm not using .on right, because it doesn't take the $('.btn') into account, only searching child events. So I find myself doing things like $('someParentElement').on or $('body').on, one being more difficult to maintain because it assumes the elements appear in a certain context(someone moves the link and now the javascript breaks) and the second method I think is inefficient.
Here is a second example that works properly in both enabled/disabled scenarios, but I feel like having to first select the parent element is really bad, because the event will break if someone rearranges the page layout:
http://jsfiddle.net/f5Ytj/32/
Don't use event delegation if you only want to listen for clicks on the .btn element itself:
$('.btn').on('click', function() {
if (!this.hasAttribute("disabled"))
alert("test");
});​
If you'd use event delegation, the button would need to be the matching element:
$(someParent).on('click', '.btn:not([disabled])', function(e) {
alert('test!!');
});​
Demo
Or use a true button, which can really be disabled:
<button class="btn" [disabled]><span class="file-icon" /> Test</button>
Demo, disabled.
Here, no click event will fire at all when disabled, because it's a proper form element instead of a simple anchor. Just use
$('.btn').on('click', function() {
if (!this.disabled) // check actually not needed
this.diabled = true;
var that = this;
// async action:
setTimeout(function() {
that.disabled = false;
}, 1000);
});​
.on('click', ':not([disabled])'
^ This means that, since the icon is a child of the button ".btn", and it is not disabled, the function will execute.
Either disable the icon, also, or apply the event listener only to the <a> tag that is your button, or use e.stopPropagation();
I would suggest using e.stopPropagation();, this should prevent the icon from responding to the click.
That doesn't seem to work for me ^
Disabling the icon, however, does.
I would prefer to add the event using delegation here as you are trying to base the event based on the attributes of the element.
You can add a check condition to see if you want to run the code or not.
$('.container').on('click', '.btn', function() {
if( $(this).attr('disabled') !== 'disabled'){
alert('test!!');
}
});​
Check Fiddle
You're not using the selector properly.
$('.btn').not('[disabled]').on('click', function () {
alert("test");
});​
See it live here.
Edit:
$('.container').on('click', '.btn:not([disabled])', function () {
alert("test");
});​
I think what you need is:
e.stopPropagation();
See: http://api.jquery.com/event.stopPropagation/
Basically something like the following should work
$('.icon-file').on('click', function(event){event.stopPropagation();});
You may want to add some logic to only stop bubbling the event when the button ist disabled.
Update:
not sure, but this selector should work:
$('.btn:disabled .icon-file')

Why my pop up is closed immediately?

I use Jquery UI to open a pop up on a click but this pop up is closed immediately.I don't understand why?
Here is my code:
function openPopUp() {
// alert("Handler for .click() called.");
$("#dialog:ui-dialog").dialog("destroy");
$("#select-method").dialog({
modal : true,
height: 573,
width: 766 ,
buttons : {
Exporter : function() {
//$(this).dialog("close");
alert("Exporter");
// close the dialog
},
'Etat de surveillance' : function() {
//$(this).dialog("close");
alert("Etat de surveillance");
// close the dialog
},
Annuler : function() {
//$(this).dialog("close");
alert("Annuler");
// close the dialog
}
}
});
};
The code html is:
<div id="other" class="popLink">This is text
<a href="" class="popLink" onClick="openPopUp();">
Click to open pop up
</a>
</div>
<div class="noDisplay">
<div id="select-method" title="selection des méthodes et calcul des provisions">My pop upis opened
</div>
</div>
Like the one comment says, try something like this:
onclick="openPopUp();return false;"
Although it would make sense, since you're already using jQuery, to bind the event with jQuery, not inline HTML. Instead of specifying the onclick attribute, try this in $(document).ready:
$(".popLink").click(function (e) {
e.preventDefault();
// Either call openPopUp or copy/paste the code from that function into here - depends on how you actually use openPopUp throughout your whole site
});
But at the same time, you have something weird in your HTML - nested divs with the same class "popLink". Which means that if you used my code above, when you click on the inner one, the showPopUp will execute twice (because of propagation). So I guess I would technically use this binding:
$("#other").on("click", ".popLink", function (e) {
e.preventDefault();
// Other code
});
This technically binds the click event to the element #other, but only is executed if caused by an element inside of it that has the class "popLink". There are several other ways to target the <a> you want, so it depends on if the code you provided is an example or is real.
Try this :)
$('.popLink').click(function(e) {
e.preventDefault();
openPopUp();
});

Categories

Resources