Measures for the code that prevents iFrame execution - javascript

I want to implement iFrames, but this pagination code gets in the way.
If I don't comment out this pagination code, iFrame will not be executed.
pagination code ( pagination.js ):
////////// this part or ↓
function tpl(data) {
var html = '';
$.each(data, function(index,item) {
html += '<section class="item">' + item + '</section>';
});
return html;
}
//////////
$(function() {
var len = $('.item').length;
$('#no-p').pagination({
dataSource: function(done) {
var result = [];
for (var i = 0; i < len; i++) {
var $item = $('.item').get(i);
if ($item) result.push($item.innerHTML);
}
done(result);
},
pageSize: 8,
showPageNumbers: false,
showNavigator: true,
autoHidePrevious: true,
autoHideNext: true,
////////// iFrame will not be executed unless this part is deleted ↓
callback: function(data,pagination) {
var html = tpl(data);
$('#items').html(html);
}
//////////
});
});
iFrame code ( iziModal.js ):
$(document).on('click', '.item1', function (event) {
$(".item1").click(function (event) {
event.preventDefault();
$('#iframe').iziModal('open');
$('#modal').iziModal('open', {
iframeURL: $(this).data('href')
});
});
$("#modal").iziModal({
iframe: true,
width: '98%',
iframeHeight: 650,
zindex: '110',
iframeURL: "data.html",
group: 'works',
overlayColor: 'rgba(0,0,0,0.1)'
});
$(".item1").off('click');
});
However, I need both iFrame and pagination.
How can I implement both?

Related

Positioning of jQuery tooltip

I´m using the jQuery UI tooltip plugin.
How can I change the tooltip position depending on the windows´ resolution?
At the moment I still need to reload the browser so the script takes effect. It can´t adjust the position in real time when changing the browser windows´ size
var res = $(window).width();
var arr = {};
if(res < 960){
arr = {my: "left+3 bottom-3", of: event, collision:"fit"};
}else{
arr = {my: "left+153 top+20", collision: "flipfit" };
}
init_tooltip(arr);
function init_tooltip(param){
$('*[data-id]').tooltip({
tooltipClass: "tooltipitem",
content: '<div class="loading">Laden...</p>',
hide: {
effect: "slideData",
delay: 0
},
position: arr,
});
}
$('*[data-id]').hover(function (event, ui) {
let $tooltip = $(this);
let id = $tooltip.attr("data-id");
ajaxManager.add({
url: "../datenbank/itemscript.php",
type: "GET",
cache: "true",
data: {
"var": id
},
success: function (data) {
console.log(data);
$tooltip.tooltip({
content: data
});
}
});
});
You could use ternary operator:
var res = $(window).width();
$('*[data-id]').tooltip({
tooltipClass: "tooltipitem",
content: '<div class="loading">Laden...</p>',
hide: {
effect: "slideData",
delay: 0
},
position: (res < 960 ? {my: "left+3 bottom-3", of: event, collision:"fit"} : { my: "left+153 top+20", collision: "flipfit" }),
});
or classic if else
var res = $(window).width();
function init_tooltip(param){
$('*[data-id]').tooltip({
tooltipClass: "tooltipitem",
content: '<div class="loading">Laden...</p>',
hide: {
effect: "slideData",
delay: 0
},
position: param,
});
}
to trap the change of window width:
$(window).resize(checkWidth);
checkWidth();
function init_tooltip(param){
$('*[data-id]').tooltip({
tooltipClass: "tooltipitem",
content: '<div class="loading">Laden...</p>',
hide: {
effect: "slideData",
delay: 0
},
position: param,
});
}
function checkWidth(){
var res = $(window).width()
var arr = {};
if(res < 960){
arr = {my: "left+3 bottom-3", of: event, collision:"fit"};
}else{
arr = {my: "left+153 top+20", collision: "flipfit" };
}
init_tooltip(arr);
}

FullCalendar events colors

I have a calendar, and outside of this I have a box where I put the event values (client, barber, service and I choose a color). After loading the values, an element is generated that I can select and drag to the calendar. The following happens to me:
When I create an event and drag it to the calendar, it is placed with the color that I configured. If I click the save button, it loads correctly into the database. A json is saved with the event information, for example:
{"id":2,"title":"Maria Marco","barbero":"Diego","servicio":"Corte","start":"2020-03-21T10:30:00","end":"2020-03-21T11:00:00","color":"rgb(0, 86, 179)"}
Suppose I don't have any items in the database, and I create 3 events and drag them to the calendar. If I click the save button, these 3 will be saved correctly as indicated above.
Now if I do a new event load, these new elements will load correctly, but in the previous elements the color property now disappears.
I appreciate if any find the error in this spaghetti of js
$(function() {
var containerEl = document.getElementById('external-events');
var calendarEl = document.getElementById('calendar');
// initialize the external events
// -----------------------------------------------------------------
new FullCalendarInteraction.Draggable(containerEl, {
itemSelector: '.external-event',
eventData: function(eventEl) {
var barbero = $("#barbero").children(".opcion-barbero:selected").html()
var servicio = $("#servicio").val()
return {
title: eventEl.innerText,
extendedProps: { "barbero": barbero, "servicio": servicio, "color": eventEl.style.backgroundColor },
backgroundColor: eventEl.style.backgroundColor,
borderColor: eventEl.style.backgroundColor
};
}
});
view = 'timeGridDay';
header = {
left: 'prev,next timeGridDay,timeGridWeek,dayGridMonth',
center: '',
right: ''
};
var calendar = new FullCalendar.Calendar(calendarEl, {
timeZone: 'local',
plugins: ['interaction', 'dayGrid', 'timeGrid'],
eventSources: [
// your event source
{
url: 'ajax/turnos2.ajax.php'
}
],
editable: true,
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function(info) {
info.draggedEl.parentNode.removeChild(info.draggedEl);
}
});
calendar.render();
/* ADDING EVENTS */
var currColor = '#3c8dbc' //Red by default
//Color chooser button
var colorChooser = $('#color-chooser-btn')
$('#color-chooser > li > a').click(function(e) {
e.preventDefault()
//Save color
currColor = $(this).css('color')
//Add color effect to button
$('#add-new-event').css({
'background-color': currColor,
'border-color': currColor
})
})
$('#add-new-event').click(function(e) {
e.preventDefault()
//Get value and make sure it is not null
var val = $('#new-event').val()
if (val.length == 0) {
return
}
//Create events
var event = $('<div />')
event.css({
'font-weight': 300,
'background-color': currColor,
'border-color': currColor,
'color': '#fff'
}).addClass('external-event')
event.html(val)
$('#external-events').prepend(event)
//Add draggable funtionality
ini_events(event)
//Remove event from text input
$('#new-event').val('')
})
/*==============================================
Apply changes to the events
==============================================*/
$(document).on("click", "span.guardarCalendario", function() {
var arrayEventos = new Array();
var eventos = calendar.getEvents();
// Contador para ID
var num = 1;
eventos.forEach(e => {
// Nombre del turno
title = (e._def["title"]);
barbero2 = (e._def.extendedProps["barbero"]);
servicio = (e._def.extendedProps["servicio"]);
color = (e._def.extendedProps["color"]);
id = num;
num = num + 1;
var evento = new Object();
evento["id"] = id;
evento["title"] = title;
evento["barbero"] = barbero2;
evento["servicio"] = servicio;
evento["start"] = start;
evento["end"] = end;
evento["color"] = (e._def.extendedProps["color"]);
arrayEventos.push(evento);
})
$("#turnos").val(JSON.stringify(arrayEventos))
var data = { 'data': JSON.stringify(arrayEventos) }
$.ajax({
type: 'POST',
url: 'ajax/turnos.ajax.php',
dataType: 'json',
data: data,
success: function(data, status, xhr) {
alert("response was " + data);
},
error: function(xhr, status, errorMessage) {
$("#debug").append("RESPONSE: " + xhr.responseText + ", error: " + errorMessage);
}
});
})
turnos.ajax.php
<?php
require_once "../modelos/turnos.modelo.php";
require_once "../controladores/turnos.controlador.php";
class AjaxTurnos{
public $data;
public function ajaxActualizarTurnos(){
$datos = ($this->data);
foreach(json_decode($datos) as $value){
$respuesta = ModeloTurnos::mdlActualizarTurnos(json_encode($value).PHP_EOL);
}
return $respuesta;
}
}
/*==============================
ACTUALIZAR TURNOS
==============================*/
if(isset($_POST["data"])){
ModeloTurnos::mdlTruncarTurnos();
$turnos = new AjaxTurnos();
$turnos -> data = $_POST["data"];
$turnos -> ajaxActualizarTurnos();
}
turnos2.ajax.php
<?php
require_once "../modelos/turnos.modelo.php";
require_once "../controladores/turnos.controlador.php";
$data = ControladorTurnos::ctrMostrarTurnos();
$data2 = [];
foreach($data as $key=>$value){
$data2[] = json_decode($value["datos"]);
}
//returns data as JSON format
echo (json_encode($data2));

Jqgrid frozen columns - can't get them to freeze unless I manually resize the grid

I have read every post I can find on Frozen columns in jqgrid. And have implemented the following code.
The result... when I go to my spreadsheet grid in my app the 3 cols are NOT frozen. BUt if I drag the little resize icon in the lower left ever so slightly then POP they 3 columns are now frozen.
Why doesn't it work when the spreadsheet is first drawn?
Here's the code:
var $grid = $("#list4");
var resizeColumnHeader = function () {
var rowHight, resizeSpanHeight,
// get the header row which contains
headerRow = $(this).closest("div.ui-jqgrid-view")
.find("table.ui-jqgrid-htable>thead>tr.ui-jqgrid-labels");
// reset column height
headerRow.find("span.ui-jqgrid-resize").each(function () {
this.style.height = '';
});
// increase the height of the resizing span
resizeSpanHeight = 'height: ' + headerRow.height() + 'px !important; cursor: col-resize;';
headerRow.find("span.ui-jqgrid-resize").each(function () {
this.style.cssText = resizeSpanHeight;
});
// set position of the dive with the column header text to the middle
rowHight = headerRow.height();
headerRow.find("div.ui-jqgrid-sortable").each(function () {
var $div = $(this);
$div.css('top', (rowHight - $div.outerHeight()) / 2 + 'px');
});
};
var fixPositionsOfFrozenDivs = function () {
var $rows;
if (this.grid === undefined) {
return;
}
if (this.grid.fbDiv !== undefined) {
$rows = $('>div>table.ui-jqgrid-btable>tbody>tr', this.grid.bDiv);
$('>table.ui-jqgrid-btable>tbody>tr', this.grid.fbDiv).each(function (i) {
var rowHight = $($rows[i]).height(), rowHightFrozen = $(this).height();
if ($(this).hasClass("jqgrow")) {
$(this).height(rowHight);
rowHightFrozen = $(this).height();
if (rowHight !== rowHightFrozen) {
$(this).height(rowHight + (rowHight - rowHightFrozen));
}
}
});
$(this.grid.fbDiv).height(this.grid.bDiv.clientHeight+1);
$(this.grid.fbDiv).css($(this.grid.bDiv).position());
}
if (this.grid.fhDiv !== undefined) {
$rows = $('>div>table.ui-jqgrid-htable>thead>tr', this.grid.hDiv);
$('>table.ui-jqgrid-htable>thead>tr', this.grid.fhDiv).each(function (i) {
var rowHight = $($rows[i]).height(), rowHightFrozen = $(this).height();
$(this).height(rowHight);
rowHightFrozen = $(this).height();
if (rowHight !== rowHightFrozen) {
$(this).height(rowHight + (rowHight - rowHightFrozen));
}
});
$(this.grid.fhDiv).height(this.grid.hDiv.clientHeight);
$(this.grid.fhDiv).css($(this.grid.hDiv).position());
}
};
var fixGboxHeight = function () {
var gviewHeight = $("#gview_" + $.jgrid.jqID(this.id)).outerHeight(),
pagerHeight = $(this.p.pager).outerHeight();
$("#gbox_" + $.jgrid.jqID(this.id)).height(gviewHeight + pagerHeight);
gviewHeight = $("#gview_" + $.jgrid.jqID(this.id)).outerHeight();
pagerHeight = $(this.p.pager).outerHeight();
$("#gbox_" + $.jgrid.jqID(this.id)).height(gviewHeight + pagerHeight);
};
$grid.jqGrid({
datatype: "local",
shrinkToFit:false,
autowidth:true,
height: 450,
hoverrows: true,
sortable: false,
colNames:[' <br> <br> <br> <br>Year',
' <br> <br> <br>Your<br>Age',
' <br> <br> <br>Spouse<br>Age',
'Your Annual<br>Job<br>Income',
'Spouse Annual<br>Job<br>Income'
colModel:[
{name:'year',index:'year', width:50, align:"center",sortable:false, sorttype:"int",classes:'spreadsheet_cell0', frozen:true},
{name:'age0',index:'age0', width:50, align:"center",sortable:false, sorttype:"int",frozen:true},
{name:'age1',index:'age1', width:50, align:"center",sortable:false, sorttype:"int",frozen:true},
{name:'salary0',index:'salary0', width:100, align:"right",sortable:false,sorttype:"float",formatter:'currency', formatoptions:{decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 0, prefix: "$"}},
{name:'salary1',index:'salary1', width:100, align:"right",sortable:false,sorttype:"float",formatter:'currency', formatoptions:{decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 0, prefix: "$"}}
],
multiselect: false,
rowNum:20,
rowList:[10,20],
altRows:false,
onSelectRow: function (id) {
if (id && id!=previous_row) {
previous_row=id;
}
},
loadComplete: function () {
fixPositionsOfFrozenDivs.call(this);
}
});
// ADD DATA TO THE GRID
addData();
$grid.jqGrid('gridResize', {
minWidth: 450,
stop: function () {
fixPositionsOfFrozenDivs.call(this);
fixGboxHeight.call(this);
}
});
$grid.bind("jqGridResizeStop", function () {
resizeColumnHeader.call(this);
fixPositionsOfFrozenDivs.call(this);
fixGboxHeight.call(this);
});
$(window).on("resize", function () {
// apply the fix an all grids on the page on resizing of the page
$("table.ui-jqgrid-btable").each(function () {
fixPositionsOfFrozenDivs.call(this);
//fixGboxHeight.call(this);
});
});
// after all that freeze the cols and fix the divs
resizeColumnHeader.call($grid[0]);
$grid.jqGrid('setFrozenColumns');
$grid.triggerHandler("jqGridAfterGridComplete");
fixPositionsOfFrozenDivs.call($grid[0]);

How to create multiple jQuery dialogs in a loop

I am trying to generate multiple jQuery Dialogs within a loop. Funny thing is, if I hardcode the dialogs in the function(), like #dialog1.dialog({...}) and #dialog2.dialog({...}) and so on it works!
But if I generate these functions in a loop it doesn't work!!!
Here is an exemplary code:
<div id=object><div>
<script type="text/javascript">
var array =['1','2','3','4','5','6','7','8'];
$(document).ready(function () {
for(var i = 0; i < 7 ; i++) {
$( "#dialog"+array[i]).dialog({
autoOpen: false,
width: "auto",
show: {
effect: "blind",
duration: 500
},
hide: {
effect: "blind",
duration: 500
}
});
$( "#opener"+array[i]).click(function() {
$( "#dialog"+array[i]).dialog( "open" );
});
}
});
for(var i = 0; i < 7 ; i++) {
$("#object").append("<button id=\opener"+array[i]+">Details</button> ");
$("#object").append("<div class=\"dialog\" id=\"dialog"+array[i]+"\"title=\"Details\"></div>");
};
</script> `
It would be very kind if someone could help me!
Include the below code in document ready function
for(var i = 0; i < 7 ; i++) {
$("#object").append("<button id=\opener"+array[i]+">Details</button> ");
$("#object").append("<div class=\"dialog\" id=\"dialog"+array[i]+"\"title=\"Details\"></div>");
}
You need to swap your loops over. At the moment you are trying to access #dialogX elements before they exist in the DOM. In fact, you can combine both loops into one, which creates the button and dialog elements and then instatiates the dialog.
var array =['1','2','3','4','5','6','7','8'];
$(document).ready(function () {
for (var i = 0; i < array.length; i++) {
var $dialog = $('<div />', {
class: 'dialog',
id: 'dialog' + array[i],
title: 'Details'
}).dialog({
autoOpen: false,
width: "auto",
show: {
effect: "blind",
duration: 500
},
hide: {
effect: "blind",
duration: 500
}
});
var $button = $('<button />', {
id: 'opener' + array[i],
text: 'Details'
}).click(function () {
$("#dialog" + array[i]).dialog("open");
});
$("#object").append($button, $dialog);
}
});

Script doesn't work on elements loaded with infinite scrolling

I'm using this script on my tumblr page, which gives posts different random text colors:
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;}
$(function() {
$(".post").each(function() {
$(this).css("color", get_random_color());
}); });
The thing is the script isn't working for elements loaded with infinite scrolling. Can anyone help me rewrite this code? I don't know how to write javascript sadly.
Take a look at your blog's main.js script. You can call your custom function when you grab the new elements from another page. This is my proposed revision of your main.js file.
$(window).load(function () {
var $wall = $('#content');
$wall.imagesLoaded(function () {
$wall.masonry({
itemSelector: '.post',
isAnimated: false
});
});
$wall.infinitescroll({
navSelector: '#pagination',
nextSelector: '#pagination li a.pagination_nextlink',
itemSelector: '.post',
loadingImg: "http://static.tumblr.com/kwz90l7/bIdlst7ub/transparent.png",
loadingText: " ",
donetext: " ",
bufferPx: 100,
debug: false,
errorCallback: function () {
$('#infscr-loading').animate({
opacity: .8
}, 2000).fadeOut('normal');
}
}, function (newElements) {
var $newElems = $(newElements);
$newElems.hide();
$newElems.each(function(value){
value.css("color", get_random_color());
});
$newElems.imagesLoaded(function () {
$wall.masonry('appended', $newElems, {
isAnimated: false,
animationOptions: {
duration: 900,
easing: 'linear',
queue: false
}
}, function () {
$newElems.fadeIn('slow');
});
});
$(document).ready(function () {
$("a[rel^='prettyPhoto']").prettyPhoto({
deeplinking: false,
default_width: 600,
default_height: 550,
allow_resize: true,
});
});
});
$('#content').show(500);
});
function get_random_color() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
What I've done is add your get_random_color function and called it from within the Infinite Scroll call to add a custom color to each of the elements in $newElems so really, all I've done is taken your code and integrated it differently than what you were trying to do, which wasn't working. This should, theoretically, work. If it doesn't or you have questions, let me know.

Categories

Resources