I am trying to add a picture and text to my JQuery Dialog box yet I am having problems, I'm new to JQuery but can't seem to find anything wrong with the code. Anyone have any ideas on what the problem is ?
$(function() {
$( ".dialog" ).click(function(){
$('#dialog').append('<img src="Image here"/><br/>').append($(this).html());
$('#dialog').html("The Football Game ") + $(this).html() + " Is now playing")dialog({
resizable:true,
modal:true,
height: 350,
width: 500,
buttons: {
"Ok": function()
{
$(this).dialog('close');
},
"Cancel": function()
{
$(this).dialog('close');
}
}
});
});
});
Using your very example, slightly rewritten.
HTML markup to trigger dialog:
<div id="dialog" title="Basic dialog">
<p>Here's some content</p>
</div>
<!-- a HTML element with the class "dialog" to trigger the event -->
<input type="button" class="dialog" value="Trigger Dialog"/>
Your jQuery example modified:
$(document).ready(function(){
$('.dialog').click(function(){ //use a better selector to trigger this event..
var fetchHTML = $('#dialog').html(); //fetch the current HTML of your element with the ID "dialog" and save it within a variable
$('#dialog').html('<img alt="" src="someimage.png"/>'+ fetchHTML); // add your image to the element and then the HTML that was there before. The method htm() will overwrite everything that was there before
$('#dialog').dialog({ //use the jquery-ui dialog method with selected parameters
resizable : true,
modal : true,
height : 350,
width : 500,
buttons: {
"Ok": function(){
$(this).dialog('close');
},
"Cancel": function(){
$(this).dialog('close');
}
}
});
});
});
And remember to make sure that you have successfully included:
jQuery
jQuery-ui
jQuery-ui CSS stylesheet (or at least the appropriate classes that you need).
Google hosts them all for you https://developers.google.com/speed/libraries/devguide. Easy as pie to just copy and paste them within your document
Whenever developing web applications I use FireFox and have installed extensions such as FireBug, WebDeveloper and YSlow. They're of great help :) Just saying...
One
The main issue I see is in the line below:
$('#dialog').html("The Football Game ") + $(this).html() + " Is now playing")dialog({
There is an extra ) which is closing the html() and you are missing a . before calling dialog().
$('#dialog').html("The Football Game " + $(this).html() + " Is now playing").dialog({
Two
Also, you are calling html() after append(), essentially overwriting the appended content. Try using append() after html() (or combine all the content into the html() call):
$('#dialog')
.html('<img src="http://dummyimage.com/600x400/000/fff"/><br/>')
.append("The Football Game "+ $(this).html() + " Is now playing")
.dialog({ ...
Working Example
Related
I"m currently using a fancybox to deliver content in a popup 2 seconds after a page loads. I'd like implement something that would remove the annoyance of this popping up every single time a page on the site is loaded.
Ideally, if a visitor clicked the "close" button on the fancybox, the pop-up wouldn't appear for them until the next day. If the visitor clicked the link that's in the popup, then the popup wouldn't appear until a specified later date.
Here's the code I'm currently using for the popup:
// fancybox arguments
$(".fancybox")
.attr('rel', 'gallery')
.fancybox({
padding : 0,
'autoDimensions': false,
'autoSize': false,
'width': '650',
'height': 'auto'
});
// Launch fancyBox on first element
setTimeout(function(){$(".fancybox").eq(0).trigger('click');},2000)
I assume this can be done using js cookie, but i'm not sure how the syntax would work based off what I'm trying to do with two different expirations .
EDIT:
Here's the HTML that is used for the pop-up:
<div style="display:none">
<a class="fancybox" href="#donation-info" alt=""/></a>
<div id="donation-info">
<?php if (get_field('donation_box_text', 'option')){
echo '<h2>To all our readers:</h2>';
echo '<p>' . get_field('donation_box_text', 'option') . '</p>';
echo '<div style="text-align:center"><a href="' . get_field('donation_link', 'option') . '" id="donate" class="donate-link" />Donate</a></div>';
}; ?>
</div>
</div>
I also tried updating the above function to include cookies, from the best of my guesstimation, to no avail:
$(document).ready(function() {
if ($.cookie('noShowDonation')) $('.fancybox').hide();
else {
$("#donate").click(function() {
// fancybox arguments
$(".fancybox")
.attr('rel', 'gallery')
.fancybox({
padding : 0,
'autoDimensions': false,
'autoSize': false,
'width': '650',
'height': 'auto'
});
// Launch fancyBox on first element
setTimeout(function(){$(".fancybox").eq(0).trigger('click');},2000)
$.cookie('noShowDonation', true);
});
}
});
EDIT #2 -- Updated code
Using the code suggested by #Rob below, I tried adding the configurations to the fancybox as well as the timeout, however, no luck. Here's the JS Fiddle: https://jsfiddle.net/30Lxfc6r/
I've updated my answer with a JSBin example based on the FancyBox docs.
https://jsbin.com/bajocosese/edit?html,console,output
http://fancyapps.com/fancybox/#docs
$(function () {
// Define cookie name
var cookieName = 'hide_donate';
// Configure fancyBox
$('.fancybox').fancybox({
autoDimensions: false,
autoSize: false,
height: 'auto',
padding: 0,
width: 650,
beforeLoad: function() {
// Returning false will stop fancybox from opening
return ! $.cookie(cookieName);
},
afterClose: function() {
// Set cookie to hide fancybox for 1 day
$.cookie(cookieName, true, { expires: 1 });
}
});
// Handle donate click event
$('a#donate').on('click', function (event) {
event.preventDefault();
// Hide fancybox and set cookie to hide fancy box for 7 days
$.fancybox.close();
$.cookie(cookieName, true, { expires: 7 });
});
// Launch fancyBox on first element
setTimeout(function () {
$(".fancybox").trigger('click');
}, 2000);
});
Remember, this example will only work once, unless you delete the cookie, or change the cookie name.
I have this dialogue box that I would like to remove the title bar because simply it looks ugly, the only problem is that the title bar contains the close button which I need. To see an example of what I am talking about, you can see it here:
kitchenova.com
Here is my code:
<script type="text/javascript">
$(document).ready(function(){
if(localStorage.getItem("firstTime")==null){
$( "body" ).prepend( "<div class='dialog-wrapper'></div>" );
$("#dialog").show();
$(".ui-dialog-titlebar").hide();
$("#dialog").dialog(
{
width:600,
height:319,
zIndex: 99999
});
$("#dialog").dialog('open');
localStorage.setItem("firstTime","done");
}
$('.ui-dialog-titlebar-close').click(function(){
$('.dialog-wrapper').remove();
});
});
</script>
And yes I have looked at the dialog widget documentation and can't seem to make sense of it for I am not too familiar with jquery. Alternatively maybe you can help me have the dialog close by click outside of the dialog.This is what I want it to look like.
You could create a button to close the dialog and get it use the following code:
$("#dialog").dialog('close');
You just need to add a close button to the initialization object:
$("#dialog-confirm").dialog({
resizable: false,
modal: true,
width:600,
height:319,
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
and instead of JavaScript to hide the titlebar you can just use css:
.ui-dialog-titlebar { display:none; }
Here is a working JSFiddle: http://jsfiddle.net/Z9wZL/
I'm pretty much a total noob to JavaScript and jQuery and I'm having trouble getting a basic dialog box working. Here is my code:
<script type="text/javascript">
$(document).ready(function() {
var dialog = $("#dialog");
dialog.dialog({
title: "Dialog",
modal: true,
draggable: false,
resizable: false,
autoOpen: false,
width: 500,
height: 400
});
dialog.hide();
});
function showDialog() {
$("#dialog").dialog("open");
}
$("ui-widget-overlay").click(function() {
$(".ui-dialog-titlebar-close").trigger("click");
});
</script>
<div id="dialog">
Dialog text.
</div>
<button onclick="showDialog()">Show Dialog</button>
When I click the button, the title bar of the dialog comes up and the background of the page dims, but there are two problems:
The body of the dialog does not show (all that shows is the title bar)
When I click outside of the dialog, the dialog does not close. I have to click the "x" in the corner in order for the dialog to close.
I've been reading tons of related questions on here, but nothing I try seems to work. Any advice?
I believe the problem you're having is from this line:
dialog.hide();
What I would suggest is removing all of the dialog content from the dialog div and populating it when you actually show the dialog.
<div id="dialog"></div>
function showDialog()
{
$("#dialog").html("Dialog Text.");
$("#dialog").dialog("open");
}
As for handling the close part, have you tried nesting everything in the main page in a <div> of its own and then handling that click event?
<div id="mainPageDiv">
</div>
$("#mainPageDiv").click(function(){
$("#dialog").dialog("close");
});
Just use a modal dialog and close the dialog when they click the overlay. Also, you should not need to put any code in $(document).ready for this.
function showDialog() {
var dialog = $("#dialog");
dialog.dialog({
title: "Dialog",
modal: true,
open: function () {
$('.ui-widget-overlay').bind('click', function () {
dialog.dialog('close');
});
}
});
}
Demonstration
I see your:
$("ui-widget-overlay").click(
perhaps should select a class:
$(".ui-widget-overlay").click(
which does not happen as it does not exist, so you need to hook it to the document.
and the dialog.hide(); is not needed as it hides it automatically when it becomes a dialog
SO you should have:
$(document).on('click',".ui-widget-overlay", function() {
$(".ui-dialog-titlebar-close").trigger("click");
});
more simply:(if you have no other dialogs you need to deal with this way)
$(document).on('click',".ui-widget-overlay", function() {
$("#dialog").dialog("close");
});
sample fiddle to show full reworked code: http://jsfiddle.net/GrFE3/2/
I am adding this as an additional answer as it goes about this differently, changing the markup, removing the in-line event handler in the markup, uses your button, and uses your dialog variable (differently than you, but...
<div id="dialog">
Dialog text.
</div>
<button id="showDialog">Show Dialog</button>
and the code for that markup:
$(document).ready(function() {
var dialog = $("#dialog");
dialog.dialog({
title: "Dialog",
modal: true,
draggable: false,
resizable: false,
autoOpen: false,
width: 500,
height: 400
});
$('#showDialog').click(function() {
dialog.dialog("open");
});
$(document).on('click', ".ui-widget-overlay", function() {
dialog.dialog("close");
});
});
I am having an issue with jQuery's Datatable plugin... I have filled a table, and a specific column has cells looking like this:
12
I have prevented the onclick event and it triggers this code:
$( 'a[name="PO"]' ).click(function(){
event.preventDefault();
var POid = $( this ).attr('href');
var element = $( this );
$( '<div id="Dialog">\
<p class="error"></p>\
<p style="text-align:center;" class="main">Entrez le P.O. associé à la commande</p>\
<input type="text" class="POprompt"/>\
</div>').dialog({
resizable: false,
height: 'auto',
width:'400',
modal: true,
title: 'Ajout d\'un PO',
show: 'blind',
hide: 'drop',
buttons:{
"Sauvegarder":function() {
$('.error').css('color','FF0000');
var prompt = $('.POprompt').val();
if (!isNaN(parseInt(prompt)))
{
$.post('setPO.php',{'PO':prompt,'id':POid},function(data)
{
element.text( prompt );
$('.main').css('color','#0F0');
$('.POprompt').css('visible','false');
$('.main').text("L\'ajout a été effectué avec succès.")
$( this ).dialog( "close" );
$('.error').text("");
$('.error').css('color','#FFF');
});
}
else
{
var error = $('.error');
error.text("Veuillez entrer des chiffres seulement.");
error.addClass( "ui-state-highlight" );
setTimeout(function() {
error.removeClass( "ui-state-highlight", 1500 );
}, 1000 );
}
$('.error').css('color','FF0000');
},
"Annuler":function()
{
$( this ).dialog( "close" );
}
}
} );
});
But when I go on page 2 or 3, or when I sort results and click on that cell link but that the row was generated in another page than the first one, the javascript does not trigger.
Anyone has an idea? Thanks a lot in advance guys, and have a nice day.
I realize that this question has been answered, however, it's incomplete and with all due respect possibly wrong. The issue with the mutipage datatable is that the initial selector is rendered useless with the user clicks on ANY of the pages other than the default first page. This is because dataTable does some horrible things to the DOM in order to render the table. This has the side effect of disabling your click handler.
The good news is that there is a way to handle this other than listing ALL elements.
instead of...
$( 'a[name="PO"]' ).click(function(){
try this:
$( "#dataTable tbody" ).on('click', 'a[name="PO"]', function(){
Read this jquery page ( on() ) and look for the section on deferred selectors.
Because when the javascript insert element to document it doesn't have onclick. jQuery will not add onclick to them, automatically.
Solution: Call this script every time data loaded (when user changes page or sorts table).
I finally got everything to work fine by adding this:
"bLengthChange": true,
to my datatable declaration.
I also modified the <select> options, adding a "show all" option which loads all the rows by default, but only shows 5 rows on pageload since I set "iDisplayLength": 5.
Here is how to add a "show all" value to your length select input (sum):
$(document).ready(function(){
$('table').dataTable({
"bLengthChange":true,
"bFilter":true,
"iDisplayLength": 5,
"sDom":'<"H"lfr>t<"F"ip>',
"oLanguage":{
"sUrl": "dataTables.txt"
}
});
});
The text file contains all your translations (if you need them) and your custom SELECT:
{
"sProcessing": "Processing...",
"sLengthMenu": "Show <select><option value=-1>INFINITE</option></select> results"
}
Note: of course I added other options to my select AND datatable declaration, it is just easier to read this way. The value=-1 part is how to get javascript to load on ALL rows/cells.
Thanks to the guys who tried helping me out, both of your answers were useful to me!
I have a table that, when any row is clicked, launches a jQueryUI modal dialog box to allow users to edit that record. I use the following script which seems to work, successfully loading the relevant record's details in using AJAX:
$("#datatbl tr").bind('click', function() {
var url = 'item_edit.asp?id='+$(this).attr("data-myid");
var dialog = $('<div style="display:hidden" title="Record details:"></div>').appendTo('body');
// load remote content
dialog.load(
url,
{},
function (responseText, textStatus, XMLHttpRequest) {
dialog.dialog({
height: 440,
width: 550,
autoOpen: false,
modal: true,
buttons: {
"Update this record": function() {
$('#editform').submit();
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
dialog.dialog('open');
}
);
//prevent the browser to follow the link
return false;
});
It works ok the first time I click on a record, but if I click cancel and try to edit another record, the dialog box does appear (with the correct record details) however, no scripts within the dialog box work - eg: there's a jqueryUI datepicker input and some validation.
There are no javascript errors and, from my limited understanding of FireBug, I can't spot anything going wrong so I would appreciate some advice how to proceed, thanks!
EDIT: Argh! Sometimes, it takes something like typing it out here to spot the obvious. I just realised that the DIV created for the dialog box doesn't get destroyed when the box closes. I've added a line to do this and it now works. Thanks for listening. :)
For future reference, I added an ID to the DIV created in 'var dialog' and removed it in the Cancel function:
Cancel: function() {
$( this ).dialog( "close" );
$('#dialogbox').remove();
}
I'd still appreciate if anybody suggests a better way to handle this behaviour.
I fixed it: the DIV created for the dialog box doesn't get destroyed when the box closes.
I added an ID to the DIV created in 'var dialog' and removed the DIV in the Cancel function:
Cancel: function() {
$( this ).dialog( "close" );
$('#dialogbox').remove();
}
You can create the dialog at one time only, not on every load of its content, just set the autoOpen to false.
<div id="dialog">
<div id="content" style="display:hidden" title="Record details:"></div>
</div>
$('#dialog').dialog({
height: 440,
width: 550,
autoOpen: false,
modal: true,
buttons: {
"Update this record": function() {
$('#editform').submit();
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
$("#datatbl tr").bind('click', function() {
var url = 'item_edit.asp?id='+$(this).attr("data-myid");
// load remote content
$('#content').load(url);
$('#dialog').dialog('open');
return false;
}};