Load a page via .load in pop-up - javascript

I'm trying to load a PHP page via jQuery. I want it to have a pop-up effect. I tried using the code below, but when the click event is triggered, it seems as if only the CSS from the imported page is being imported. The page content does not appear, but the look changes due to CSS conflicts.
I'd like the page to load and not conflict with the other CSS
function previewPop(){
$(".pop").click(function(){
$("iframe#preview").load("templates/1.php",
function(){$("iframe#preview").fadeIn(300); })
});
};

<div id="frame_wrapper">
</div>
$(".pop").click(function(){
var the_iframe = '<iframe id="my_iframe" src="' + templates/1.php + '" height="500px" width="500px">';
$('#frame_wrapper').append(the_iframe);
});
I hate dealing with iframes, so sometimes it's just easier to create a new one and destroy it as necessary.

Related

Javascript / jQuery: Detect when each individual image loads

I'm creating a loading bar for my website and I want to update the loading progress (%) with each image load. For testing purposes, I used console.log() (instead of updating my loading bar).
I want to detect when each individual image loads. My images are all within <div id='images>
I have not found a solution that has worked after 5 hours of searching. I'm new to jQuery & Javascript, so I may have been using incorrect syntax (such as not targetting the image container correctly, but I'm not sure.
I have tried the imagesloaded jQuery plugin, but when using $('#images').imagesLoaded(), imagesloaded had said that all images had loaded, when they hadn't. (I'm testing using two 4k images so I can see the images slowly load).
The imagesloaded jQuery code I used for testing (loadProgress.js):
$('#images').imagesLoaded() //My images are within "<div id='images></div>"
.always( function( instance ) {
console.log('all images loaded');
})
.done( function( instance ) {
console.log('all images successfully loaded');
})
.fail( function() {
console.log('all images loaded, at least one is broken');
})
.progress( function( instance, image ) {
var result = image.isLoaded ? 'loaded' : 'broken';
console.log( 'image is ' + result + ' for ' + image.img.src );
});
// Code I used to keep track of when the page actually loaded
console.log('Page load started')
window.onload = function() {
console.log('Page load complete')
My HTML (Images were for testing purposes only and may be copyright) [just a snippit, not including doctype, body etc]:
<script src="https://unpkg.com/imagesloaded#4/imagesloaded.pkgd.min.js"></script>
<script scr="loadProgress.js"></script>
<div style="text-align:center" id="images">
<img src="https://wallpapers.gg/wp-content/uploads/2018/01/Old-Lion-4K.jpg" alt="Lion 4K" id='image' />
<img src="https://images7.alphacoders.com/383/383230.jpg" alt="Lion 4K" id="image" />
</div>
Console output [comment]:
Page load started
all images loaded
all images successfully loaded
[a good 5 second delay]
Page load complete
The output looks promising as the images are said to load after the page load has begun, but there is a 5 second delay between all images successfully loaded and Page load complete where I can see the images slowly render top-to-bottom and can also see the spinning loading icon in my browser tab (indicating that the images have not loaded yet, as there is no other html to load). I believe that the plugin is not correctly detecting the images container.
How can I (preferably automatically, not having to assing a unique ID to each image, and for them to collectively be found) detect when each individual image has loaded?
I'd like my console output to be (for example with two images):
Page load started
Image loaded
Image loaded
[no delay]
Page load complete
I am not looking to detect when all images have been loaded, and specifically want to repeat an action each time an image is loaded. In this case, the action would be console.log('Image loaded')
Using either Javascript or jQuery isn't a problem, and if you know a plugin which can achieve this more efficiently, I'd love to know.
I am not sure about the jQuery plugin you are using, but you could register an "onload" function to each image you want to load. No additional plugins/libraries needed, plain JavaScript should be fine.
Ideally, you would do it on backend side, not frontend, since images might be already loaded (think of browser cache) at the moment you assign the "onload" function.
If you want to target every image, just use the $('img') as your selector. If not, target their container element an you should be good to go.

Nivo Lightbox function in Ajax loaded content

I'm having trouble making jquery function to work in AJAX loaded content. Function is for adding additional youtube parameters to src link. I'm using Nivo Lightbox for youtube links. This code works fine in not dynamically loaded content:
$('.video_btn_slider').nivoLightbox({
afterShowLightbox: function(lightbox){
var src = $('.nivo-lightbox-content > iframe').attr('src');
$('.nivo-lightbox-content > iframe').attr('src', src + '?autoplay=1'+'&showinfo=0'+'&rel=0');
}
});
I managed to make it work only wrapping it with:
$(document).bind('DOMNodeInserted', function(e) {...});
But DOMNodeInserted is deprecated.
Therefore, need your advice. Maybe in general there is a better solution.

Print function only works after second click

I have this function to print a DIV.
Whenever the page is loaded and I click in a "Print" link I have, the DIV is shown to be printed without CSS.
If I close Chrome's print visualization page and click in the "Print" link again, the DIV has CSS applied.
Any ideas why?
Javascript
function printDiv(divId) {
var printDivCSSpre =
'<link href="/static/assets/vendor/sb-admin-2-1.0.7/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">' +
'<link href="/static/assets/vendor/sb-admin-2-1.0.7/dist/css/sb-admin-2.css" rel="stylesheet">' +
'<div style="width:1000px; padding-right:20px;">';
var printDivCSSpost = '</div>';
$('body').append('<iframe id="print_frame" name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>');
$("link").clone().appendTo($("#print_frame").contents().find("head"));
window.frames["print_frame"].document.body.innerHTML =
printDivCSSpre + document.getElementById(divId).innerHTML + printDivCSSpost;
window.frames["print_frame"].window.focus();
var windowInstance = window.frames["print_frame"].window;
windowInstance.print();
}
HTML
<a id="print" href="#">
<i class="fa fa-print"></i> Print
</a>
<script>
$('#print').click(function () {
printDiv('report')
})
</script>
<div id="report" class="report">
<p># Generated Table#</p>
</div>
First click:
http://imgur.com/a/Go81Y
Closing the print preview page and clicking again in print
http://imgur.com/a/SCxJF
This happens because when you call your printDiv() function, css is also written using inner HTML and in this scenario CSS is not applied during first click because you wrote CSS to the elements even when they do not exist inside DIV.
The function to work as desired has to write DIV contents first and then CSS should be applied. I would say write css after contents of DIV or load on top of your HTML page and just write DIV contents.
Hope that helps.
Every thing is right just change the sequence. In browser debugger on first click it didn't show 'print_frame' in sources section while in second click it does (I am using chrome devtool).
So load in memory frame with css attributes during onload:
var windowInstance;
$(function(){
$('body').append('<iframe id="print_frame" name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>');
$("link").clone().appendTo($("#print_frame").contents().find("head"));
windowInstance = window.frames["print_frame"].window;
});
and onClick just append html
$('#print').click(function () {
var divId = 'report';
var printDivCSSpre ='<div id="printReportDiv" style="width:1000px; padding-right:20px;">';
var printDivCSSpost = '</div>';
window.frames["print_frame"].document.body.innerHTML = printDivCSSpre + document.getElementById(divId).innerHTML + printDivCSSpost;
window.frames["print_frame"].window.focus();
windowInstance.print();
});
updated jsfiddle
Try this one. The problem mainly arises because the css has not been applied to the page when the print command is initiated. setTimeout is one way to solve it as others have mentioned but it is really not possible to predict how much delay you will need. Slow internet connections will require high delays before you fire the print statement. The following code, however, only fires the print event after the css has been properly applied to the iframe.
$('#print').click(function () {
if($("#print_frame").length == 0) {
$('#report').after('<iframe id="print_frame" name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>');
}
var $head = $("#print_frame").contents().find("head");
// for now for ease I will just empty head
// ideally you would want to check if this is not empty
// append css only if empty
$head.empty();
$.ajax({
url : "https://dl.dropboxusercontent.com/u/7760475/reports.css",
dataType: "text",
success : function (reports) {
// grab css and apply its content to the iframe document
$head.append('<style>'+reports+'</style>');
$.ajax({
url : "https://dl.dropboxusercontent.com/u/7760475/bootstrap.css",
dataType: "text",
success : function (bootstrap) {
// grab another css and apply its content to the iframe document
// there may be better ways to load both css files at once but this works fine too
$head.append('<style>'+bootstrap+'</style>');
// css has been applied
// clone your div and print
var $body = $("#print_frame").contents().find('body');
// empty for ease
// but later append content only if empty
$body.empty();
$("#report").clone().appendTo($body);
$('#print_frame').get(0).contentWindow.print();
}
});
}
});
});
Use inline CSS instead.
Reason: When we PRINT or save as PDF if fails to fetch external css Files, So we have to use Inline css.
edited your file please see: jsfiddle.net/ytzcwykz/18/
As other people mentioned it is hard to see your problem without seeing the working example of a problem, but just guessing from the code:
Browser is not able to load the CSS before your print() call.
Browser is not able to render the CSS before your print() call.
Keeping that in mind changing your JS function that way might do the trick
function printDiv(divId) {
$("link").clone().appendTo($("#print_frame").contents().find("head"));
window.frames["print_frame"].document.body.innerHTML =
printDivCSSpre + document.getElementById(divId).innerHTML + printDivCSSpost;
window.frames["print_frame"].window.focus();
var windowInstance = window.frames["print_frame"].window;
setTimeout(function() {
windowInstance.print();
}, 0);
}
The idea behind this function is to let browser execute it's code after we added changed the HTML/CSS code in the window - see Why is setTimeout(fn, 0) sometimes useful?
WARNING: this approach is not tested for your particular problem, and it might also not work because we escape/leave the mouse-click call-stack, calling print() method might be not possible out of user-interaction stack.
UPDATE: after looking in the posted jsfiddle - my assumption was correct, the browser needs some time to load and render the CSS, that is why calling the print() right after changing iframe contents doesn't give the desired result. There are 3.5 ways to solve that:
Use events to identify when iframe's document and window has finished loading and rendering. I tried two approaches, and failed so far, need to read docs more carefully about when document and window are behiving during the loading sequence:
we can do that from outside of iframe, i.e. listen to events of iframe element and it's children
we can do that from inside of iframe, i.e. add little javascript snippet inside which will send a message to the parent window when loading is done.
Consider forming the print result different, how about print style-sheets? I.e. add one more style sheet with print-media query to the parent doc and just call print on it?
Consider forming an iframe which is already loaded and ready to be printed, but replace just the table contents inside it.
As others mentioned, The problem here is that the CSS files used are external resources and browser takes time to download and cache it locally. Once it is cached, it would serve faster and that's why it works fine from the second click.
As Anton mentioned, setTimeout is the key here! You may probably increase the timeout seconds to make that work. I tried setting it to 500ms and that worked,
setTimeout(function(){windowInstance.print();},500);

Pre Load images to display later on click event jQuery

I have a web page where lots of images called from server using image
scr attribute.
I have created a function like which is triggered by td click.
function GoToStep(stepNo) {
var imgSrc = $("#h1" + stepNo).val();
$(".img_vertical").css("background-image", "url(" + imgSrc + ")");
}
Now the problem is this. For slower connections the images come after some
moment.
Can I pre load images to avoid waiting time when user clicks
td?
I have seen some jquery function to pre load images.
Kindly give some idea how can I achieve it.
Pre-loading an image is equivalent to loading an image but never displaying it. So, you can easily do it like this:
<img src="image.png" alt="" style="display:none;"/>
Now this image will be loaded as soon as the html starts rendering. Whenever you need to use this image as a display or background, just set the address to image.png and it will automatically be fetched from browser's cache.
This can be done using some javascript functions. Quoting from another question.
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
// Alternatively you could use:
// (new Image()).src = this;
});
}
// Usage:
preload([
'img/imageName.jpg',
'img/anotherOne.jpg',
'img/blahblahblah.jpg'
]);
Explanation of how javascript preloaders work (different question)
[...] The way it works is simply by creating a new Image object and setting
the src of it, the browser is going to go grab the image. We're not
adding this particular image to the browser, but when the time comes
to show the image in the page via whatever method we have setup, the
browser will already have it in its cache and will not go fetch it
again. [...]
So in your case, you should use something like
$(function() {
// Do stuff when DOM is ready
preload([
'img/bg1.jpg',
'img/bg2.jpg',
'img/bg3.jpg'
]);
});

printing iframe content with jquery

i have an iframe:
<iframe name="printarea" id="printarea" src="print.php" style="display: none;"></iframe>
i need this iframe to have the style "display: none;" so it is invisible
now when someone clicks a link generated via php:
echo '<img src="images/icon-print.png" alt="" />';
i want it to simply change the iframe SRC and print what is in the iframe, however my code is not working at all:
function print_receipt (id)
{
$('#printarea').attr('src', 'print.php?id='+id);
$('#printarea').focus();
$('#printarea').print();
}
so this is what i want:
- user clicks on link
- iframe content changes based on the link he clicks
- iframe content prints
2 issues:
you'll maybe need to wait until the page is loaded
print() is a method of window-objects
$('#printarea')
.load(function(){this.contentWindow.print();$(this).unbind('load');})
.attr('src', 'print.php?id='+id);
What is $('#printarea').focus(); supposed to achieve? As far as I know .focus() works with form elements and links...
What is $('#printarea').print();? Haven't come across that function in jQuery. If you're using a plugin it would help to mention which one.
So perhaps you'll have more luck with:
function print_receipt (id)
{
$('#printarea')
.attr('src', 'print.php?id='+id)
.css("display","block");
}

Categories

Resources