Setting Fancybox2 width/height dynamically - javascript

I am trying to use fancybox v2 to show a div whose contents are generated dynamically. I set the size of the div quite late in the scheme of things. I have tried the examples from fancybox's documentation for displaying divs whose size is fixed. It looks like this:
<a id="fancy" href="#showdiv">Show contents of div.</a>
<div id="showdiv">...</div>
<script>
$(document).ready(function() {
$("#fancy").fancybox({autoSize:false, width: W, height: H, ...});
});
</script>
What I want is W=$("#showdiv").width and H=$("#showdiv").height. Obviously, H and W are not available to me at document ready. How do I go about doing this?
EDIT: Here is the html for the content div:
<div id="hidediv" style="display:none">
<div id="showdiv" style="display:block;position:relative">
<canvas id="mycanvas" style="position:relative;display:block"></canvas>
</div>
</div>
In a click handler of the anchor "#fancy" I do:
function onclick() {
var jcanvas = $("#mycanvas").css('width', some_width).css('height', some_height);
// draw on canvas
}
"#fancy" is the one associated with Fancybox.

Assuming that this function handles the response of your HTTP POST
function onclick() {
// set size of canvas
var jcanvas = $("#mycanvas").css({
"width": some_width, // variable from response ?
"height": some_height
});
// draw on canvas
}
... then call that function using the fancybox afterLoad callback like
$("#fancy").fancybox({
fitToView: false, // the box won't be scaled to fit the view port (optional)
afterLoad: onclick()
});
EDIT :
Another option is to handle both, the canvas and fancybox within the same function using jQuery .on() so if you have
<a id="fancy" href="#showdiv">Show contents of div</a>
use this script :
$("#fancy").on("click", function () {
// do HTTP POST
// on success, get size form response
var some_width = 300,
some_height = 180;
// set canvas size
var jcanvas = $("#mycanvas").css({
// variables from response
"width": some_width,
"height": some_height
});
// draw on canvas
//
// then open fancybox ($(this) = #showdiv )
$.fancybox($(this),{
// API options etc
fitToView: false
});
});
in this case you don't need any callback.
NOTE : .on() requires jQuery v1.7+
See JSFIDDLE for documentation purposes.

Related

Detecting scroll event of Iframe called by AJAX reqest

i have a link in my main page that uses ajax to retrieve a PDF which is displayed in an Iframe, i am trying to detect scroll event of the PDF document and display a message or do something. i have tried different solutions from other solutions on stackoverflow and google search in general and couldn't find a good solution.
Main.php
<html>
<!--ajax request-->
<script type="text/javascript">
$(document).on('click','#nextpdf',function(event) {
event.preventDefault();
var reg = $(this).attr("href");
var str = reg.split('?')[1];
$.ajax({
type: "GET",
url: '../functions/pdfreader.php',
data: 'pdfxs='+str+'',
cache:false,
async: false,
success: function(data) {
// data is ur summary
$('.refresh').html(data);
return false;
}
});//end of ajax
});
</script>
<?php
while($obj = $c_content->fetch())
{
$title = $obj['lecture_title'];
echo '<article class="comment2">
//pdf link
<div class="comment2-body">
<div class="text" style="color:#999;padding-right:130px;">
<p><a href="../functions/pdfreader.php?'.$title.'""
style="color:#999" id="nextpdf">'.$title.'</a></p>
</div>
</div>
</article>
';
}
?>
</html>
pdfreader.php
//detect iframe pdf scroll
<script type="text/javascript">
$("myiframe").load(function () {
var iframe = $("myiframe").contents();
$(iframe).scroll(function () {
alert('scrolling...');
});
});
</script>
<?php
........
while($obj = $gettrend->fetch())
{
$coursefile = $obj['lecture_content'];
//this is my iframe
echo '<div class="mov_pdf_frame"><iframe id="myiframe"
src="https://localhost/einstower/e-learn/courses/pdf/'.$coursefile.'"
id="pdf_content"
width="700px" height="800px" type="application/pdf">
</iframe></div>';
}
?>
The major problem here is that nothing happens when i scroll the pdf document, how can i detect scrolling?
i found this fiddle that works but i cant view the javascript solution. http://fiddle.jshell.net/czw8pbvj/1/
First off, $("myiframe") isn't finding anything, so it attaches a load event to nothing. 1) change it to $("#myiframe") or $("iframe").
Here's a working fiddle (for iframe scroll detection)
UPDATE: to detect the scroll within PDF document, you can't use iframe. For that, you need embed or object tags AND a JS-enabled PDF document (hopefully its your PDFs..), who can send messages to your page's JS (see this answer).
Unfortunately, I couldn't find a scroll event in Adobe's Acrobat API Reference. It lists only these events:
Event type: Event names
App: Init
Batch: Exec
Bookmark: Mouse Up
Console: Exec
Doc: DidPrint, DidSave, Open, WillClose, WillPrint, WillSave
External: Exec
Field: Blur, Calculate, Focus, Format, Keystroke, Mouse Down, Mouse Enter, Mouse Exit, Mouse Up, Validate
Link: Mouse Up
Menu: Exec
Page: Open, Close
Screen: InView, OutView, Open, Close, Focus, Blur, Mouse Up, Mouse Down, Mouse Enter, Mouse Exit
So, basically, I think what you want just isn't possible as for now, at least with default rendering. With custom rendering (https://github.com/mozilla/pdf.js) it could be possible, though I'm not sure.
Apparently, it could be done with page scroll (see this issue). So back to iframes solution. :^D
Because this question is asked a long time ago, i think i need to help with my experience before.
The answer is: You can not
Why? because PDF is rendered by external apps, such as adobe pdf reader, foxit or else. And you can not attach event on them.
if you are using adobe reader, The only you can do is goto page, change zoom etc. Full example you can read here: https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf#page=8 (see. i bring you to page 8 directly instead to first page).
But, hei.. how if our client using another apps? we will confused more
The way to do this is only build your own pdf viewer.
we can using js library, like: http://www.bestjquery.com/2012/09/best-jquery-pdf-viewer-plugin-examples/
but here i only will show you to use pdf.js which created by mozilla.
main.php
<style>
.preview{
display:none;
width: 400px;
height: 400px;
border: 1px solid black;
}
</style>
file/test.pdf<br>
file/test1.pdf<br>
<div class="preview">
<iframe id="myiframe" frameborder="0" width="400px" height="400px" >not support iframe</iframe>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(document).on('click', '#nextpdf', function(e){
e.preventDefault();
$('#myiframe').attr('src', $(this).attr('href'));
$('.preview').show();
});
//handle iframe on scroll
$('#myiframe').on('load', function () {
$(this).contents().scroll(function () {
console.log('scrolled');
}).click(function(){
console.log('clicked');
});
});
});
</script>
pdfreader.php
<?php
$path = 'file/';
$pdf = isset($_GET['pdfxs']) ? $path . $_GET['pdfxs'] : '';
if(!file_exists($pdf) || !mime_content_type($pdf) =='application/pdf') die('file not found');
?>
<div id="pdf-container">
<div id="pdf-box"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
<script>
$(function(){
//original script : https://gist.github.com/fcingolani/3300351
function renderPDF(url, canvasContainer, options) {
var options = options || { scale: 1 };
function renderPage(page) {
var viewport = page.getViewport(options.scale);
var canvas = $(document.createElement('canvas'));
var renderContext = {
canvasContext: canvas[0].getContext('2d'),
viewport: viewport
};
canvas.attr('width', viewport.width).attr('height', viewport.height);
canvasContainer.append(canvas);
page.render(renderContext);
}
function renderPages(pdfDoc) {
for(var num = 1; num <= pdfDoc.numPages; num++)
pdfDoc.getPage(num).then(renderPage);
}
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(renderPages);
}
renderPDF('<?=$pdf;?>', $('#pdf-box'));
});
</script>
Note: i put pdf on folder file/
in main.php you will notice that you can attach event scroll (and click too) to the pdf. because our pdf is not rendered by external apps now.
and the last part is, if you read pdfreader.php carefully, you will notice that you no need iframe anymore. You just need div, and then you can fully handle all event that do you want to your pdf : like scroll, click, change page, zoom, etc. why?? because your pdf is redered as canvas now (pdf.js render your pdf as HTML5 canvas). see full example of pdf.js
Please try this
iframe.on( "scroll", handler )
$("#frame").scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height())
alert('Bottom reached');
});
I found this in the JSFiddle that was referenced in the Fiddle you linked. The HTML field is empty. This CSS was in there, too.
body {
height: 1500px;
}
In the fiddle that you linked, the <iframe> has an ID of frame. I figured you can use the jQuery selector like $("#frame").
I think this will help you.
$("#myiframe").load(function () {
$(this).contents().scroll(function () {
//your code here
});
});

jQuery Hide Class

I have a web page that is loading images and scans across about 600+ images as the user presses next or previous. This is working fine. However, the image load time is slow so the idea is to put a processing while in place of the images until they are fully loaded. I can get the processing wheel to load perfectly fine but I cannot get it to hide once the image or document is loaded. I have tried doing this two different ways:
Attempt 1:
$('#centerImage').ready(function () {
$('.spinner').css('display', 'none');
});
Attempt 2:
$('#centerImage').ready(function () {
$('.spinner').hide();
});
I have also tried replacing the selector #centerImage on the .ready() function with document but still don't see the Processing Wheel get hidden.
What I find strange is that when I try and hide an ID instead of a Class, it works perfectly fine. I tried a 'Try Me' on W3 Schools with a simple example and hiding a class with the .hide() doesn't work there either.
Google isn't returning anything specific to any limitations with jQuery hiding classes. Is this possible or am I approaching this the wrong way?
NOTE: I'm using spin.js for the processing wheel.
All Code:
JavaScript:
EDIT: Added .load instead of .ready
var previousImage = document.getElementById("previousImage");
var centerImage = document.getElementById("centerImage");
var nextImage = document.getElementById("nextImage");
previousImage.setAttribute("src", "../.." + document.getElementById("MainContent_lblPreviousImage").innerHTML);
centerImage.setAttribute("src", "../.." + document.getElementById("MainContent_lblCenterImage").innerHTML);
nextImage.setAttribute("src", "../.." + document.getElementById("MainContent_lblNextImage").innerHTML);
$('#centerImage').load(function () {
$('.spinner').hide();
});
HTML/ASP.NET:
<div id="images">
<img id="previousImage" onload="showProgress()" alt="" src=""/>
<img id="centerImage" onload="showProgress()" alt="" src=""/>
<img id="nextImage" onload="showProgress()" alt="" src=""/>
</div>
Show Progress JavaScript File:
function showProgress () {
var opts = {
lines: 13, // The number of lines to draw
length: 20, // The length of each line
width: 10, // The line thickness
radius: 30, // The radius of the inner circle
corners: 1, // Corner roundness (0..1)
rotate: 0, // The rotation offset
direction: 1, // 1: clockwise, -1: counterclockwise
color: '#000', // #rgb or #rrggbb or array of colors
speed: 1, // Rounds per second
trail: 60, // Afterglow percentage
shadow: false, // Whether to render a shadow
hwaccel: false, // Whether to use hardware acceleration
className: 'spinner', // The CSS class to assign to the spinner
zIndex: 2e9, // The z-index (defaults to 2000000000)
top: '50%', // Top position relative to parent
left: '50%' // Left position relative to parent
};
var target = document.getElementById('images');
var spinner = new Spinner(opts).spin(target);
}
Thanks in advance for any helpful input.
As #Barmar $("#centerimage").ready() is the same as $(document).ready(). There's no separate ready event for each element, it just applies to the whole DOM.
Ready is used to check if the DOM is ready and the load is used to check if the Content is loaded.
Use load instead of ready:
$('#centerImage').load(function () {

html2canvas - no screenshot for iframe

I have a task where i need to load a URL (e.g www.yahoo.com) , on my webpage, and take screenshot. I am using html2canvas for screenshot and appending it to the body of the page.
The page specified by the URL is successfully loaded in an iframe inside a div element. But when i try to take screenshot of that, the iframe area comes blank.
Below is the code for previewURL and screenshot.
//to preview the URL content
function previewUrl(url,target){
//use timeout coz mousehover fires several times
clearTimeout(window.ht);
window.ht = setTimeout(function(){
var div = document.getElementById(target);
div.innerHTML = '<iframe style="width:100%;height:100%;" frameborder="0" src="' + url + '" />';
},20);
}
function pic() {
html2canvas(document.body, {
onrendered: function(canvas) {
document.body.appendChild(canvas);
}
});
};
And the HTML part goes here :
<body>
<input type="button" class="clear-button" onclick="pic();" value="Take Screenshot" >
Hover to load
<div id="div1"></div>
</body>
The screenshot looks something like this :
I am stuck and don't understand why is this happening. I want something similar to this which can load URL and then onclick can give me screenshot.
The problem here is that you are not pointing correctly to the part of the iframe that you want to take the screenshot, instead you are pointing directly to the document body.
you can try this:
var body = $(iframe).contents().find('body')[0];
html2canvas(body, {
onrendered: function( canvas ) {
$("#content").empty().append(canvas);
},
Hope this helps!
Seems like it's not possible:
The script doesn't render plugin content such as Flash or Java applets. It doesn't render iframe content either.
http://html2canvas.hertzen.com/documentation.html#limitations
This code worked 4 me:
setTimeout(() => {
html2canvas($('#'+idd2).contents().find('body')[0], {
allowTaint : true,
logging: true,
profile: true,
useCORS: true
}).then(function(canvas) {
document.getElementById('screen').appendChild(canvas);
}); }, 3000);

How to load image on demand

I have this simple image zoom jQuery. Here is a Demo example. It uses the elevateZoom jQuery.
The code behind is very simple:
<img id="zoom_05" src='small_image1.png' data-zoom-image="large_image1.jpg"/>
<script>
$vc("#zoom_05").elevateZoom({
zoomType : "inner",
cursor: "crosshair"
});
</script>
My question, is how can i make the large image load on demand, only when the mouse is over it. Please have a look at this demo example and let me know what i need to add in the code.
img element (id="zoom_05") above, would not load large_image1.jpg on its own.
Large image load happens because elevateZoom() looks into its data-zoom-image value and immediately loads it. One way around this behaviour is to defer elevateZoom() until user hover's over the small image for the first time. Quick example:
jQuery( function () {
var elevate_zoom_attached = false, $zoom_05 = $("#zoom_05") ;
$zoom_05.hover(
// hover IN
function () {
if ( ! elevate_zoom_attached ) {
$zoom_05.elevateZoom({
zoomType : "inner",
cursor : "crosshair"
});
elevate_zoom_attached = true ;
};
},
// hover OUT
function () {
if ( elevate_zoom_attached) { // no need for hover any more
$zoom_05.off("hover");
}
}
);
}) ;
Mind you this is an quick, on-top-of-my-head code, but should work ...
Also in this case elevateZoom() action might not be immediate while large image loading is going on.
I used this idea to initiate zoom on any number of images on the same page by adding a zoom class to the image. It works without any HOVER OUT
<img class="zoom" src="myimage.png" data-zoom-image="mybigimage.png"/>
$('.zoom').hover(
// hover IN
function () {
var currImg = $(this); //get the current image
if (!currImg.hasClass('zoomon')) { //if it hasn't been initialized
currImg.elevateZoom(); //initialize elevateZoom
currImg.addClass('zoomon'); //add the zoomon class to the img so it doesn't re-initialize
}
})

Save canvas to image via toDataURL failed

I create a test code below and you can manipulate it on Jsfiddle:
http://jsfiddle.net/Stallman41/57hvX/31/
HTML:
<canvas id="test_canvas" style="background-color : #FFFF00" ; width="500px"
; height="340px"></canvas>
<br>
<button id="test_put_btn">Put an image</button>
<br>
<button id="save_dataURL">Save to dataURL</button>
<br>
<button id="draw_back">Final step: draw 3 images back.</button>
<br>
<img id="first_img"; width="100px" ; height="100px" ;></img>
<img id="second_img"; width="100px" ; height="100px" ></img>
<img id="third_img"; width="100px" ; height="100px" ;></img>
Javascript:
var drawing_plate;
var context;
var dataURL_arr = new Array();
$(document).ready(function () {
drawing_plate = document.getElementById("test_canvas");
context = drawing_plate.getContext('2d');
$("#test_canvas").bind("mousedown", Touch_Start);
$("#test_canvas").bind("mousemove", Touch_Move);
$("#test_canvas").bind("mouseup", Touch_End);
}); //document ready.
function Touch_Start(event) {
event.preventDefault();
touch = event;
touch_x = touch.pageX;
touch_y = touch.pageY;
line_start_x = touch.pageX - 0;
line_start_y = touch.pageY - 0;
context.beginPath();
context.moveTo(line_start_x, line_start_y);
}
function Touch_Move(event) {
event.preventDefault();
touch = event; //mouse
line_end_x = touch.pageX - 0;
line_end_y = touch.pageY - 0;
context.lineTo(line_end_x, line_end_y);
context.stroke();
}
$("#test_put_btn").click(function () {
var test_img = new Image();
test_img.src = "http://careerscdn.sstatic.net/careers/gethired/img/careers2- ad-header-so-crop.png";
context.drawImage(test_img, 0, 0);
});
$("#save_dataURL").click(function () {
dataURL_arr.push(drawing_plate.toDataURL("image/png"));
});
$("#draw_back").click(function () {
var f_image= $("#first_img")[0];
var s_image= $("#second_img")[0];
var t_image= $("#third_img")[0];
f_image.onload= function()
{
f_image.src= dataURL_arr[0];
}
f_image.src= dataURL_arr[0];
s_image.onload= function()
{
s_image.src= dataURL_arr[0];
}
s_image.src= dataURL_arr[0];
t_image.onload= function()
{
t_image.src= dataURL_arr[0];
}
t_image.src= dataURL_arr[0];
});
I develop a drawing plate on Android system, saving the drawings to a dataURL string. They can draw something on the canvas and put images on the canvas. And I need to let the users see their drawings on small icons.
I use canvas.toDataURL("image/png") to save the base64 string. And I choose <img> as the small icon container. However, what I got is only the drawings can be shown on the icon, and usually, when I write img.src= canvas.toDataURL("image/png"); the image shows nothing!
I investigate the issue for long time.
1. I think the problem might be the dataURL string is too long?
2. The support of the OS: Android?
The code in Jsfiddle here shows a similar procedure on my Android PhoneGap development.
First , you just draw something on the canvas, and press Press an image, and then Save to dataURL. But you should do the process three times. In this condition, the string array contains the base64 string generated by the drawings and the image.
In the final, you press Final step: draw 3 images back., nothing will be shown on the image icon.
In conclusion:
In my experience, as I write img.src= canvas.toDataURL("image/png"); (no matter the img is an dom element or var img = new Image();). It can't always work: sometimes it works... but sometimes not...(I work on Android 4.0.1, phonegap 1.7.0)
Second, especially if I store lots of base64 strings to an array, assigning them to lots of image DOM element, it definitely fails.
Third, if the user only draw something on the canvas, it can always work.( Except the example code in the Jsfiddle, but it works on my Android system...)
But if he draw an image context.drawImage(~) the image wouldn't show the pic.
Too much confusions...
I need to let the user can view their drawings in small icon, any alternative?
Some References:
1
2
3
I just stumbled across this question.
Click Put an image, then click Save to dataURL, then check your JavaScript console for something like:
SecurityError: DOM Exception 18
It's a browser security feature. Because you've inserted an image from a different domain, it counts as a cross-origin request.
If you eliminate the security error, you can export the canvas to a data URL.
Another thing in your code.
The image you try to draw onto the canvas into your test_put_btn onclick event handler, your image will never show up (or it will sometimes work accidentally) because you don't wait for your image to be loaded to draw it onto the canvas.
You have to handle the "onload" event of your image and draw it into the handler to permit the drawing of your image.
Before your test_img.src statement, you have to put :
test_img.onload = function()
{
context.drawImage(test_img, 0, 0);
};
Plus, the image you try to access is not accessible --> For me it does not work

Categories

Resources