image in magnific popup in iframe - iframe

i have a magnific popup being displayed dynamically but the image is rendered after the load event so i cannot get the value of the image in the open event. is there any onload event in magnific popup?
function OpenPopup(el) {
var temp = el.innerHTML;
var mysrc = $(temp).attr("src");
var isobj = $.magnificPopup.open({
items: {
src: mysrc,
onload: 'myevent()',
},
type: 'iframe',
closeOnBgClick: false,
markup: '<div class="mfp-iframe-scaler">' +
'<div class="mfp-close"></div>' +
'<iframe class="mfp-iframe" frameborder="0" onload="myevent()"></iframe>' +
'<div class="mfp-bottom-bar">' +
'<div class="mfp-title"></div>' +
'</div>' +
'</div>',
callbacks: {
beforeOpen: function () {
console.log('Start of popup initialization');
},
elementParse: function (item) {
// Function will fire for each target element
// "item.el" is a target DOM element (if present)
// "item.src" is a source that you may modify
debugger;
console.log('Parsing content. Item object that is being parsed:', item);
},
change: function () {
console.log('Content changed');
console.log(this.content); // Direct reference to your popup element
},
resize: function () {
console.log('Popup resized');
// resize event triggers only when height is changed or layout forced
},
open: function () {
console.log('Popup is opened');
debugger;
var iframe = $.magnificPopup.instance,
t = $(iframe.currItem.el[0]);
var contents = iframe.contents();
$(contents).css('max-width', '100%');
$(contents).css('max-height', '100%');
}
}
});

Not a proper solution put i added a timed event which resizes the image once it is loaded. Had to play a lot to get the perfect time so that there is no glitch.
Here is the code:
function OpenPopup(el) {
var temp = el.innerHTML;
var mysrc = $(temp).attr("src");
var isobj = $.magnificPopup.open({
items: {
src: mysrc,
},
delegate: 'a',
type: 'iframe',
closeOnBgClick: false,
});
setTimeout(setImage, 500);
};
function setImage() {
var iframe = $('.mfp-iframe');
var contents = iframe.contents();
$(contents).find('img').attr('width', '100%');
$(contents).find('img').attr('height', '100%');
}

Related

fullcalendar v5 after edit event render() don't refresh

when i edit a event list, it correctly reload but calendar don't refresh.
if i click in other tab and then return in calendar tab it refresh: problem with bootstrap? This is my function to init calendar
function getCalendar(mydate) {
//Date for the calendar events (dummy data)
var date = new Date()
var d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear()
var calendar = FullCalendar.Calendar;
var calendarEl = document.getElementById('calendar');
var calEv=bindEvents(mydate);
//var calRi=bindResource(mydate);
dCal = new calendar(calendarEl, {
schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
timeZone: 'UTC',
height: '100%',
contentHeight: 'auto',
initialView: 'dayGridMonth',
themeSystem: 'bootstrap',
locale: 'it',
//Random default events
//events: 'https://fullcalendar.io/demo-events.json',
//events: bindEvents(mydate),
//events: calEv,
//events: evUrl,
events: function(info, successCallback, failureCallback) {
var evUrl = window.apiurl+'/api/anagrafiche/tourfascecalevents/'+id_entita;
$.ajax(evUrl, {
type: 'GET',
cache: false,
}).done(function(dati) {
dbgConsole("render init ev");
dbgConsole(dati);
ev=bindEvents(dati);
dbgConsole(ev);
successCallback(ev);
}).fail(function(x,s,t) {
alert_error(x);
});
},
//resources: bindResource(mydate),
initialDate: dataIni,
editable : true,
selectable: true,
droppable : false, // this allows things to be dropped onto the calendar !!!
dateClick: function(info) {
dbgConsole(info);//event.setProp( name, value )
var cls=[];
var data_fine = moment(info.dateStr, "YYYY-MM-DD").add(gg_viaggio, 'days').format('YYYY-MM-DD');
if ('undefined' == typeof grpSelected || ''==grpSelected) {
// alert('Cancellazione data: ' + info.dateStr + ' !');
var reqUrl = window.apiurl+'/api/anagrafiche/tourfasce/'+id_entita;
$.ajax(reqUrl, {
type: 'DELETE',
cache: false,
data: {
id_gruppo: id_gruppo,
id_entita: id_entita,
MM_delete: 'form_fascedel',
data_inizio: info.dateStr
}
}).done(function(dati) {
window.tables['FasceTable'].setData();
dbgConsole("render");
//$('#h-tab').trigger('click');
//$('#dati-fasce-tab').trigger('click');
dCal.render();
//dCal.updateSize();
}).fail(function(x,s,t) {
alert_error(x);
});
} else {
// alert('Imposta data: ' + info.dateStr + ' in gruppo "'+grpSelected+'" !');
var reqUrl = window.apiurl+'/api/anagrafiche/tourfasce/'+id_entita;
$.ajax(reqUrl, {
type: 'PUT',
cache: false,
data: {
id_gruppo: id_gruppo,
id_entita: id_entita,
MM_update: 'form_fasceupd',
data_inizio: info.dateStr,
nome_periodo: grpSelected,
data_fine: data_fine
}
}).done(function(dati) {
window.tables['FasceTable'].setData();
dbgConsole("render");
//$('#h-tab').trigger('click');
//$('#dati-fasce-tab').trigger('click');
dCal.render();
//dCal.updateSize();
}).fail(function(x,s,t) {
alert_error(x);
});
}
// alert('Gruppo: ' + id_gruppo + ' - Entita: "'+id_entita+ ' - Giorni: "'+gg_viaggio+'" !');
//dCal.setOption('initialDate', '2021-06-01');
//dCal.render();
},
/*
eventClick: function(calEvent, jsEvent, view) {
var testo='';
testo=testo+'Servizio: ' + calEvent.title_serv+'\n';
testo=testo+'Inizio: ' + calEvent.start.format()+'\n';
testo=testo+'Fine: ' + calEvent.end.format()+'\n';
testo=testo+'Descrizione: ' + calEvent.title+'\n';
alert(testo);
}
*/
});
//dCal.render();
dbgConsole("Cal:")
dbgConsole(dCal);//event.setProp( name, value )
}
and this is activation
$('#dati-fasce-tab').on('shown.bs.tab', function (event) {
dCal.render();
})
after 'dateClick' events are modified and reloaded but calendar not update view
P.S.: all events are type 'background'
Already exists any different method to refresh?
We are a problem to refresh on load calendar in hidden area, any idea?
First of all, you need to render the fullcalendar element inside the initialize function.
function getCalendar(mydate) {
...
dCal = new calendar(calendarEl, {
});
dCal.render();
}
After that, you need to use refetchEvents function while an event like changing tab or save an event is firing.
https://fullcalendar.io/docs/Calendar-refetchEvents
dCal.refetchEvents();
You could face into an issue like dCal is undefined, then you need to add some handling like
if (typeof dCal !== 'undefined') {
dCal.refetchEvents();
}

How to add google map and other charts in the gridstack widget using knockout.js

I am using Gridstack with Knockout.js. I am using http://troolee.github.io/gridstack.js/demo/knockout.html to create Gridstack widgets. I added a Google map in one of these widgets. The map appears with a scroll bar. Also, I need to have some kind of heading, as it is in its present state. The main problem is that the dimension of the map is fixed and when I resize the widget, the map does not fit in the widget automatically. Here is my full code:
ko.components.register('dashboard-grid', {
viewModel: {
createViewModel: function (controller, componentInfo) {
var ViewModel = function (controller, componentInfo) {
var grid = null;
this.widgets = controller.widgets;
this.id = controller.id;
this.afterAddWidget = function (items) {
if (grid == null) {
grid = $(componentInfo.element).find('.grid-stack').gridstack({
auto: false,
animate: true
}).data('gridstack');
}
var item = _.find(items, function (i) { return i.nodeType == 1 });
grid.addWidget(item);
ko.utils.domNodeDisposal.addDisposeCallback(item, function () {
grid.removeWidget(item);
});
};
};
return new ViewModel(controller, componentInfo);
}
},
template:
[
'<div class="grid-stack" data-bind="foreach: {data: widgets, afterRender: afterAddWidget}">',
' <div class="grid-stack-item" data-bind="attr: {\'data-gs-x\': $data.x, \'data-gs-y\': $data.y, \'data-gs-width\': $data.width, \'data-gs-height\': $data.height, \'data-gs-auto-position\': $data.auto_position}">',
' <div class="grid-stack-item-content" >',
' <header style="background-color: green;"> ',
' <button data-bind="click: $root.deleteWidget">Delete me</button><br>',
' <label><strong data-bind="text: $root.ids"></strong></label>',
' </header>',
' <div data-bind="attr: {id: $root.ids}">',
' </div>',
' </div>',
' </div>',
'</div> '
].join('')
});
$(function () {
var ids;
var Controller = function () {
var self = this;
this.widgets = ko.observableArray([]);
this.id = ko.observable("google-map");
this.ids = "";
this.addNewWidget = function () {
this.ids = this.id(); // this.ids is used to give id to div elements
this.widgets.push({
x: 0,
y: 0,
width:4,
height:5,
auto_position: true,
});
// calling method to draw map
createWidget(this.ids);
return false;
};
this.deleteWidget = function (item) {
self.widgets.remove(item);
return false;
};
};
ko.applyBindings(new Controller());
});
function createWidget(id) {
var dataArray, latitude, longitude, speed;
// Load the Visualization API and the corechart package.
try {
google.charts.load('current', {'packages':['map', 'gauge']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
}
catch ( err ) {
//console.log(err);
}
function drawChart() {
latitude = Number(12.93213);
longitude = Number(77.695185);
var mapOptions = {
showTooltip: true,
showInfoWindow: true,
zoomLevel: 16, // range: 0-21 for "roadmap" map type
mapType: 'roadmap',
enableScrollWheel: true,
draggable: false,
};
var coordinates = "Latitude : " + latitude + "\nLongitude : "+ longitude;
var mapData = google.visualization.arrayToDataTable([
['Lat', 'Long', 'Name'],
[latitude, longitude, coordinates]
] );
try {
//var chart = new google.visualization.Gauge(document.getElementById('gauge'));
var map = new google.visualization.Map(document.getElementById(id));
map.draw(mapData, mapOptions);
}
catch (err) {
console.log(err);
}
} // drawChart() ends here
} // createWidgets() ends here

CSS not being applied as soon as we resize the window. It's only applied on scroll

I am using angular way to apply css but it doesn't get applied whenever resize the window. canvas height is changed on resize window but table height only being applied when we scroll the window. I want to set the same height of canvas as soon as we resize the window.
How can I fix this?
angular.element(document).ready(function ($timeout) {
function update_table_height(canvasHeight) {
angular.element('.scrollableContainer').css("height", canvasHeight + 5 + "px");
}
angular.element(window).on("load resize scroll", function() {
var canvasHeight = angular.element('#chartCanvas').height();
update_table_height(canvasHeight);
});
$timeout(function(){
var canvasHeight = angular.element('#chartCanvas').height();
update_table_height(canvasHeight);
});
});
I think you need another timeout to wait for the render.
Maybe like this:
angular.element(window).on("load resize scroll", function() {
updateHeight();
});
function updateHeight(){
$timeout(function(){
var canvasHeight = angular.element('#chartCanvas').height();
table_height(canvasHeight);
});
}
// updateHeight on load
updateHeight();
Finally I did it with help of directive. Please suggest is that okay?
in index.html
<div class="ibox-content" match-window-height="['#chartCanvas']">
in app.directive.js
.directive('matchWindowHeight', function($timeout, $window) {
return {
restrict: 'A',
link: function (scope, el, attrs) {
var window = angular.element($window);
scope.$watch(function () {
var attribute = scope.$eval(attrs['matchWindowHeight']);
var targetElem = angular.element(document.querySelector(attribute[0]));
return targetElem.height();
},
function (newValue, oldValue) {
if (newValue != oldValue) {
el.css('height', newValue + 40 );
}
});
window.bind('load resize', function () {
scope.$apply();
});
}
};
});

Best way to load css for partial views loaded using ajax

I'm working on my application that creates tabs dynamically and fills them with partial views using ajax.
My question is: how to load css for this views? What's the best way to do it? I mean I can't load the css file on the partial view (no head) or could i?
Some code: the tabManager (a partial view loaded on the main page):
<script>
var tabTemplate = "<li class='#{color}'><a id='#{id}'href='#{href}'>#{label}</a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>"; // base format for the tabs
$(document).ready(function () {
var tabs = $("#tabs").tabs(); // apply jQuery ui to tabs
$("a.menuButton").click(function () {
var urlContent = $(this).data("direction");
var label = $(this).data("label");
var idTab = $(this).data("id");
var color = $(this).data("color");
var exist = false;
var counter = 0;
$('#tabs ul li a').each(function (i) { // tab already exist o no hay que crear una tabla?
counter = counter + 1; // index counter
if (this.id == "#" + idTab) { // Tab already exist?
exist = true;
$("#tabs").tabs("option", "active", counter - 1); //activate existing element
}
});
if (idTab == "-1") { // is a clickable element?
exist = true;
}
if (exist == false) { // create new tab
addTab(idTab, label, color); // basic tab
getTabContent(idTab, urlContent); // content for new tab
var lastTab = $('#tabs >ul >li').size() - 1; // get count of tabs
$("#tabs").tabs("option", "active", lastTab); // select last created tab
}
});
function getTabContent(idT, urlC) { // ajax call to partial view
$.ajax({
url: urlC,
type: 'GET',
async: false,
success: function (result) {
$("#"+idT).html(result);
}
});
};
function addTab(idT, labT, color) { //create new tab
var label = labT,
id = idT,
li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label).replace(/#\{id\}/g, "#" + id).replace(/#\{color\}/g, color)),
tabContentHtml = "Cargando...";
tabs.find(".ui-tabs-nav").append(li);
tabs.append("<div id='" + id + "'><p>" + tabContentHtml + "</p></div>");
tabs.tabs("refresh");
}
// close icon: removing the tab on click
tabs.delegate("span.ui-icon-close", "click", function () {
var panelId = $(this).closest("li").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
});
tabs.bind("keyup", function (event) {
if (event.altKey && event.keyCode === $.ui.keyCode.BACKSPACE) {
var panelId = tabs.find(".ui-tabs-active").remove().attr("aria-controls");
$("#" + panelId).remove();
tabs.tabs("refresh");
}
});
});
</script>
<div id=tabs>
<ul>
</ul>
A button example:
<li><a class="menuButton" href="#" title="Permisos" data-id="tab3" data-direction="Permiso/_Administrar" data-label="Label" data-color="blue"><img src="#Res_icons.More">Permisos</a><li>
i found my answer here: http://dean.resplace.net/blog/2012/09/jquery-load-css-with-ajax-all-browsers/
the code:
<script type="text/javascript">
$(document).ready(function () {
$("head").append("<link href='...' rel='stylesheet'>");
});
</script>

jQuery UI map - panTo user location

Long time reader/ first time poster here, with a question I suspect will be easy to answer but help me out no end.
I simply want to i) retrieve the user's location, ii) display an icon at this location, and iii) Have a button labelled 'Find Me' that pans the map to this location.
I have i) and ii) working, but although I have other buttons that pan to a particular location, this one doesn't seem to work:
var viewportHeight = $(window).height();
var mapHeight = viewportHeight - 93;
var map;
var union = new google.maps.LatLng(53.806828, -1.555999);
var userLocation;
var userIcon = 'userIcon.png';
var parkinson = new google.maps.LatLng(53.808, -1.553);
var unionDescription = '<div id="content">' + '<div id="siteNotice">' + '</div>' + '<h2 id="firstHeading" class="firstHeading">Your Union</h2>' + '<div id="bodyContent">' + '<p>Heres a bit about us</p>' + '</div>' + '</div>';
//Try and get the user's location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
$('#map_canvas').gmap('addMarker', {
'position': userLocation,
'bounds': false,
'icon': userIcon
});
});
};
//initialise the map
$(function () {
$('#map_canvas').gmap({
'center': union,
'zoom': 16,
'mapTypeId': google.maps.MapTypeId.ROADMAP,
'styles': campusStyles,
'minZoom': 15,
'maxZoom': 17
}).bind('init', function (ev, map) {
$('#map_canvas').gmap('addMarker', {
'position': parkinson,
'bounds': false
}).click(function () {
$('#map_canvas').gmap('openInfoWindow', {
'content': 'Hello World!'
}, this);
});
$('#map_canvas').gmap('addMarker', {
'position': union,
'bounds': true
}).click(function () {
$('#map_canvas').gmap('openInfoWindow', {
'content': unionDescription
}, this);
});
$('#map_canvas').height(mapHeight);
google.maps.event.trigger(map, 'resize');
$('#unionButton').click(function () {
map.panTo(union);
});
$('#findMe').click(function () {
map.panTo(userLocation);
});
$('#map_canvas').height(mapHeight);
});
});
Thing I'm actually working on here: http://jdp.org.uk/tests/mapstest4.html
I don't know why but my navigator geolocation is not working, so I just bypassed that requirement and hard-coded a user LatLng. What worked for me was cutting and pasting the whole block if(navigator.geolocaton) to directly below the block with the line $('#unionButton').click(function(){map.panTo(union);});. It appears that map was not yet defined where you had the geolocation code.
From my testing, smooth panning only happens when the current position is close to the target. http://jsfiddle.net/EejRt/
I have:
$('#map_canvas').height(mapHeight);
google.maps.event.trigger(map, 'resize');
$('#unionButton').click(function(){map.panTo(union);});
$('#map_canvas').height(mapHeight);
//if (navigator.geolocation) {
// navigator.geolocation.getCurrentPosition(function(position) {
// var userLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var userLocation = new google.maps.LatLng(53.8018,-1.553);
$('#map_canvas').gmap('addMarker', {'position': userLocation, 'bounds': false, 'icon' : userIcon });
$('#findMe').click(function(){map.panTo(userLocation)});
// });
// };

Resources