Magnific popup does not work on second page of Datatables - javascript

I have created a datatables and add an image column into datatables. When i click image, i would like to image open at popup. It is work on for first page of datatable, however when i passed to second page, it doesn't work. Also i put alert() to test second page event and alert() works, but popup does not.
Please check my snippets: https://jsfiddle.net/f08qdeq2/20/
How can i solve this problem, any ideas? Thank You
$(document).ready(function() {
var table = $('#datatable').dataTable({
aLengthMenu: [
[1, 2],
[1, 2]
],
iDisplayLength: 1
});
});
$(this.document).ready(function() {
$('.image-popup').magnificPopup({
type: 'image',
closeOnContentClick: true,
closeBtnInside: false,
fixedContentPos: true,
image: {
verticalFit: true
},
zoom: {
enabled: true,
duration: 300 // don't foget to change the duration also in CSS
},
});
});
$(document).on('click', '.image-popup', function() {
alert('You Clicked Image');
//$('.image-popup-no-margins').magnificPopup({
//Some Working code here
//});
})

You should use fnDrawCallback for initialize your popup. try this...
$(document).ready(function() {
var table = $('#datatable').dataTable({
aLengthMenu: [
[1, 2],
[1, 2]
],
iDisplayLength: 1,
"fnDrawCallback": function () {
$('.image-popup').magnificPopup({
type: 'image',
closeOnContentClick: true,
closeBtnInside: false,
fixedContentPos: true,
image: {
verticalFit: true
},
zoom: {
enabled: true,
duration: 300 // don't foget to change the duration also in CSS
},
});
}
});
});
$(document).on('click', '.image-popup', function() {
alert('You Clicked Image');
})
Result : https://jsfiddle.net/cmedina/f08qdeq2/21/

just adding this will work for normal click event, based on this you can do anything with model(pop-up).
$(document).on('click', '.image-popup', function() {
alert('You Clicked Image');
})

Related

editurl:'client array' data to be shown in jqgrid but should not save that data to database

var specificatonsData = [];
function initGridForTransactions(gridID, gridPagerID) {
var grid_selector = gridID;
var pager_selector = gridPagerID;
$(window).on('resize.jqGrid', function () {
$(grid_selector).jqGrid('setGridWidth', $("#page-wrapper").width());
})
var parent_column = $(grid_selector).closest('[class*="col-"]');
$(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
setTimeout(function () {
$(grid_selector).jqGrid('setGridWidth', parent_column.width());
}, 0);
}
})
$(grid_selector).jqGrid({
data: specificatonsData,
datatype: "local",
colNames: ['Id','Specification', 'Abbreviation'],
colModel: [
{ name: 'Id', width: 80,key:true },
{ name: 'specification', index: 'Id', key: true, width: 300 },
{ name: 'abbreviation', width: 300 },
],
cmTemplate: { editable: true },
cellsubmit: 'clientArray',
editurl: 'clientArray',
viewrecords: true,
rowNum: 4000,
gridview: true,
rowList: [4000],
pager: pager_selector,
altRows: true,
loadonce: true,
multiselect: false,
multiboxonly: false,
sortname: 'Specification',
sortorder: "asc",
cellEdit: false,
iconSet: "fontAwesome",
onSelectRow: function (rowId, status, e) {
var dealerFeatures = $("#editor").text();
var selectedFeature = rowId;
selectedFeature = selectedFeature.replace(/(\s+)/, "(<[^>]+>)*$1(<[^>]+>)*");
var pattern = new RegExp("(" + selectedFeature + ")", "gi");
dealerFeatures = dealerFeatures.replace(pattern, "<mark>$1</mark>");
//dealerFeatures = dealerFeatures.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\/mark>)/, "$1<mark>$2</mark>$4");
dealerFeatures = dealerFeatures.replace(/(<mark>[<>]*)((<[>]+>)+)([<>]*<\/mark>)/, "$1<mark>$2</mark>$4");
dealerFeatures = dealerFeatures.replace(/\n/g, '<br>\n');
$("#editor").html(dealerFeatures);
},
gridComplete: function () {
$(grid_selector).setColProp('Approve', { editoptions: { value: '' } });
},
loadComplete: function () {
var table = this;
setTimeout(function () {
updatePagerIcons(table);
enableTooltips(table);
}, 0);
},
}).navGrid(pager_selector, { edit: true, add: true, del: false },
{
url: '/Activity/SaveSpecification',
closeAfterAdd: true,
closeAfterEdit: true,
afterSubmit: function () {
getAbbrData();
return [true, '', ''];
}
});
jQuery(grid_selector).sortableRows();
function updatePagerIcons(table) {
var replacement =
{
'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
};
$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
var icon = $(this);
var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
})
}
function enableTooltips(table) {
$('.navtable .ui-pg-button').tooltip({ container: 'body' });
$(table).find('.ui-pg-div').tooltip({ container: 'body' });
}
$(document).one('ajaxloadstart.page', function (e) {
$(grid_selector).jqGrid('GridUnload');
$('.ui-jqdialog').remove();
});
}
I will save data to database only when I click on external Submit button.
When I click on edit button the data is showing in a popup and when I click on the save button the data is getting to the database and showing in the jqgrid.
But I have a new requirement where I have to show the data in the jqgrid when click on save button but should not save to the database.
Thanks in advance.
If you use Guriddo jqGrid JS then you can set url in edit options in your navigator to be clientArray - i.e
...navGrid(pager_selector, { edit: true, add: true, del: false },
{
url: 'clientArray',
closeAfterAdd: true,
closeAfterEdit: true,
afterSubmit: function () {
getAbbrData();
return [true, '', ''];
}
});
This will save the data locally.
The code, which you posted contains many small bugs. For example,
you use url: '/Activity/SaveSpecification' as form Edit options (not for Add form) - see navGrid call. You should remove the option to make editurl: 'clientArray' working
you use key:true in more as one column. It's not allowed. One can use it only in one column, which contains unique values.
the usage of index: 'Id' property in colModel for the column name: 'specification' is probably one more bug, which can make wrong sorting and filtering in the column.
your current code contains call of .setColProp('Approve', { ... });, which is wrong, because your colModel don't contains the column 'Approve'
the option sortname: 'Specification' is wrong too, because the value of sortname should be the value of name property from colModel (like sortname: 'specification' for example, if you'll remove index: 'Id' property from the column).
Additionally the usage of rowNum: 4000 can essentially reduce the performance of the grid in case of large grid. If real number of rows is about 4000, then it's much more effective to use local paging of data. The monitor allows to display only about 20-25 rows. Thus it's recommended to use pager with such small rowNum. Users can use paging buttons to go to the next page.

Open the Results of Autocomplete in Fancybox

I have the following autocomplete searchbox code
$("#searchbox").autocomplete({
source: function(request,response) {
$.ajax({
type: "POST",
dataType: "json",
data: { term: request.term },
url: "/Settings/Find?searchString="+request.term,
success: function(data) {
response($.map(data,function(item) {
return { label: item.Name ,value: item.Type, ID: item.ID};
}
))
}
})
},
messages: {
noResults: "No Results",results: "Results"
},
select: function(e, ui) {
window.location.assign('/Item/Details/'+ui.item.ID);
}
},
});
When the user clicks on the autocompleted items, I redirect them to the detail page of the item using this
window.location.assign('/Item/Details/'+item.ID);
Now, I want to display the details of the item in a fancybox without redirect the user to another page. So when the user clicks on the autocompleted results, a fancybox opens up with the details of the selected item.
Here is the fancybox code That i would like to call.
$('.fancyboxdisplay').fancybox({
fitToView: false,
autoSize: false,
closeClick: false,
width: '550px',
height:'680px',
padding: 15,
closeBtn:true,
'afterClose': function() {
window.location.reload();
},
});
I looked everywhere for a possible solution but i can't figure it out. Can you please help !
Thanks
Within your select setting, try replacing window.location.assign by the fancybox script like :
select: function (e, ui) {
// window.location.assign('/Item/Details/' + ui.item.ID);
$.fancybox({
href: '/Item/Details/' + ui.item.ID,
type: "iframe",
fitToView: false,
autoSize: false,
closeClick: false,
width: 550,
height: 680,
padding: 15,
closeBtn: true,
afterClose: function () {
window.location.reload();
}
});
}
It's assumed you have previously loaded fancybox js and css files

Dynatree is stuck loading the icon

I use dynatree to display a list of documents. When I load the template, the dynatree was stuck in the loading icon. What could be wrong?
$("#tree").dynatree({
checkbox: true,
selectMode: 2,
initAjax: {
url: "/getTree/",
dataType: "json",
data: {}
},
onSelect: function(node) {
},
onActivate: function (node) {
},
persist: true,
noLink: false,
fx: { height: "toggle", duration: 200 },
onPostInit: function (isReloading, isError) {
if (getStringOfSelectedTreeNodes() != '') {
}
}
}); });
</script>
Did you have an example maybe on CodePen to check what the issue is. It seems the last }); end braces was not needed, was this because it was within a jQuery $(document).ready(); method. Otherwise this would be the correct code: Some good examples on the dynatree example page which I'm sure you've seen.
$("#tree").dynatree({
checkbox: true,
selectMode: 2,
initAjax: {
url: "/getTree/",
dataType: "json",
data: {}
},
onSelect: function(node) {
},
onActivate: function (node) {
},
persist: true,
noLink: false,
fx: { height: "toggle", duration: 200 },
onPostInit: function (isReloading, isError) {
if (getStringOfSelectedTreeNodes() != '') {
}
}
});

Datatables I can't call an onclick event after I paginate?

I am using http://datatables.net/
The demo table on their homepage resembles pretty much the exact same thing that i'm using (pagination, specifically), except each row has an area to click:
<%= Post.title %>
This link opens a jquery UI modal dialog which displays some information which is ajax requested.
Part 1 (solved), see part 2 below
I'm trying to run an onclick event which works normally on page one, but as soon as i go to page 2 (or any others) it stops working. I checked the source to make sure it wasnt doing anything funny in all the code is infact there (all the rows, even the ones hidden by the pagination)
Any ideas?
$(function() {
$('#dialog').dialog({
autoOpen: false,
resizable: false,
maxHeight: 600,
width: 650,
modal: true,
beforeClose: function close() {
$('#dialog').html('');
}
});
$('.show-post').click(function() {
clickLink(this);
return false;
});
});
Thanks to those who answered my question! I fixed that issue.
Part 2
my next 'issue' id like to get to work is... I'm using the left and right arrow keys to allow them to 'scan' to the next or previous row, and display the information. This is as opposed to closing it and then having to click the next one.
I'd like to make it so when you get to the bottom of page one, or top of page two, hidding next/previous respectively will automatically load that page, go to the top (or bottom), then open that dialog for that row on the other page.
heres my click function (i know its kind of probably not structured the best... im new to jquery)
$(document).ready(function() {
oTable = $('#posts').dataTable({
"bJQueryUI": true,
"iDisplayLength": 400,
"bAutoWidth": false,
"sPaginationType": "full_numbers",
"aLengthMenu": [[-1, 400, 100, 50], ["All", 400, 100, 50]]
});
$(this).keydown(function(e) {
var id = $("#dialog").attr("data-id");
currentPost = $("#posts tr[data-id=" + id + "]");
if (e.keyCode == 39 && $('#dialog').html() != "") {
/* Remove current background */
$(currentPost).blur()
$(currentPost).removeClass("current");
$(currentPost).find("td.sorting_1").removeClass("current");
var next = currentPost.next().find(".show-post");
clickLink(next);
} else if (e.keyCode == 37 && $('#dialog').html() != "") {
/* Remove current background */
$(currentPost).removeClass("current");
$(currentPost).find("td.sorting_1").removeClass("current");
var prev = currentPost.prev().find(".show-post");
clickLink(prev)
}
});
});
heres the actual click function
function clickLink(src) {
var post = $(src);
var id = $(post).parent().parent().attr('data-id');
/* Set background for current line */
$(post).parent().parent().find("td.sorting_1").addClass("current");
$(post).parent().parent().addClass("current");
$('#dialog').attr("data-id", id);
$('#dialog').load('/show-post/' + id, function() {
$.ajax({
type: "POST",
url: "/checkstatus/" + id,
dataType: "html",
error: function(data){
$("#dialog").fadeOut("fast", function() {
$("#dialog").html("<img src='/img/invalid.jpg' alt='invalid' style='margin: 40px auto; display: block;'>").fadeIn("slow");
});
}
});
/* Set Visited */
$(post).parent().parent().removeClass("visited").addClass("visited");
$('#dialog').dialog({
title: post.html(),
beforeClose: function close() {
$(post).parent().parent().find("td.sorting_1").removeClass("current");
$(post).parent().parent().removeClass("current");
},
buttons: {
"Email 1": function() {
$.ajax({
type: "POST",
url: "/get-email/" + id + "/" + "1",
dataType: "html",
success: function(data) {
window.location.href = data + "&subject=" + post.html();
}
});
},
}
});
$('#dialog').dialog('open');
});
return false;
};
The example on the link you provided appears to be adding/removing DOM elements, meaning that elements on subsequent pages probably are not in the DOM on page load. Have you tried using event delegation?
$(<root element>).delegate('.show-post', 'click', function() {
clickLink(this);
return false;
});
Where <root element> can be document but should be set to an ancestor element that is always in the DOM.
.delegate():
Attach a handler to one or more events for all elements that match the
selector, now or in the future, based on a specific set of root
elements.
Source: http://api.jquery.com/delegate
UPDATE
Note that .delegate() is an alias of .on() now, so if you're using jQuery 1.7+ I would just use .on() right from the get-go. Almost the same syntax except the selector and event are swapped: $(<root element>).on('click', '.show-post', function() { ... });
Source: Thanks Greg Pettit, Excellent Comment
Below Code is working Perfectly. When you click the pagination button 'drawCallback' class Call some function after table load.
$("#YourTableID").dataTable({
bJQueryUI: false,
bFilter: false,
bSearchable: false,
bInfo: false,
bAutoWidth: false,
bDestroy: true,
"oLanguage": {
"sEmptyTable": "No Records Found"
},
"sPaginationType": "full_numbers",
"bLengthChange": false,
"iDisplayLength": 5,
aaData: arrv,
aoColumns: [{
sTitle: "Select",
orderable: false,
className: 'select-checkbox',
targets: 0
},
{
sTitle: "Course name"
}, {
sTitle: "Level"
}, {
sTitle: "Study Mode"
}, {
sTitle: "Entry Year"
}, {
sTitle: "Point of Entry"
}, {
sTitle: "Awarding qualification"
}],
drawCallback: function () {
//Some function...
},
select: {
style: 'os',
background: 'color:gray',
selector: 'td:first-child'
},
order: [[1, 'asc']],
});
As #scrappedcola pointed out in the comments, your click handler is lost after pagination. There is a drawCallback function for DataTables you can implement which will fire after the table is "re-drawn" (hence drawCallback). Here is an example:
$('#someId').DataTable({
lengthMenu: [ 25, 50, 100, 200 ],
order: [[ 0, 'asc' ]],
processing: true,
serverSide: true,
stateSave: true,
responsive: true,
bDestroy: true,
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
],
drawCallback: function() {
var api = this.api();
api.$('#someBtnId').click(function() {
// do some click handler stuff
});
}
});

How to hide qtip tooltip after some time has passed?

I'm using qtip ( http://craigsworks.com/projects/qtip/ ) to make tooltips. Now I need to show tooltips when the button is pressed and hide tooltips for example when 3 seconds have passed. My current code is not working, tooltips will sometimes go away and sometimes stay...
var self = $("#email");
self.qtip({
content: error,
tip: true,
position: { corner: { target: 'rightMiddle', tooltip: 'leftMiddle' } },
style: 'error',
show: { when: false, ready: true },
hide: { when: { event: 'mousemove' }, delay: 2000, effect: function () { self.qtip("destroy"); } }
});
#newbie, but a response, is to tidy the code and that maybe that's the problem. eg replacing the name of the variable "self" by "this".
$("#email").qtip( {
content: error,
tip: true,
position: { corner: { target: 'rightMiddle', tooltip: 'leftMiddle' } },
style: 'error',
show: { when: false, ready: true },
hide: { when: { event: 'mousemove' },
delay: 2000,
effect: function() { $(this).qtip("destroy"); }
}
});

Categories