why document.ready not always work? - javascript

I have this very simple function to resize a div according to an element on the page.
Because of the static navigation bar on top of the page, I need to control the empty space underneath it, for the first div with content to appear on the right place (below the navigation bar), specially because when the screen is smaller, the navigation bar gets larger (height is bigger).
My question is: why does it not always work? It works fine most of the times, but sometimes I need to refresh the page for it to work.
Here is the dummy HTML:
<div id="menu-fixed-top"></div>
<div id="empty-space"></div>
<div id="content"></div>
where the #empty-space is the div I want to control the height.
I used the document.ready and the window.resize to control it.
The JQuery function is:
$(document).ready(function() {
var height = $("#menu-fixed-top").innerHeight();
$("#empty-space").height( height );
$(window).resize(function() {
$("#empty-space").height( height );
});
});
Is there any way to get it working 100% of the time? Or the only way is to be sure is to use media queries?
Thanks

document.ready will trigger when the whole DOM has loaded and is ready for javascript to execute. This is to avoid any problems with javascript being ready to go but the whole DOM hasn't finished loading.
http://learn.jquery.com/using-jquery-core/document-ready/
I would first check to see that the DOM has finished loading without document.ready being triggered before drawing the conclusion that jquery isn't kicking it off.
You may also want to look at window.load if you're wanting to calculate heights and such as the DOM != the fully rendered page

Related

Force a refresh of masonry grid

I have a script that is creating a grid, and the grid elements are "re-positioned" every time the viewport width is changed. I don't have access to the script, nor did I write it. I think it's a Masonry grid.
I'm dynamically changing the content of the grid, so I need to somehow "refresh" (re-calculate) the grid without refreshing the page. On mobile I did this by changing the "initial-scale" meta tag (then resetting it) to force the grid to update. However the viewport tag is ignored on desktop, so I don't know how to actually make the browser think that page dimensions are changed and force a refresh on the grid.
Any ideas are appreciated, thanks.
Depending on how the script is setup you may be able to simply trigger the resize event causing it to recalculate based on the current size. If the script is actually tracking the size and checking for changes then you will need to find the best way to force the script to perform it's grid recalculation, which means examining the script. It might be as simple as changing the value of the variable where the script is storing the previously recorded viewport width right before you trigger the resize event.
FYI: If the script is loading on your page then you do have access to the script.
window.addEventListener("resize", function(){
// Resize event listener from masonry script
console.log("Masonry grid resized for width "+window.innerWidth);
});
// If using jQuery
$(window).trigger("resize");
// Plain JS version
window.dispatchEvent(new Event('resize'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If the masonry script is good it may have an API feature to do what you need, however I think you'd explore that already.
Alternatively...
Option #1: Modify a parent container
See if you can force a refresh by simply temporarily modifying a parent container. For example, increase container width by 1 pixel for an instant, and return back to the original width.
Option #2: Find the existing listener; find the functions
The existing script probably has a listener + actions for when the viewport changes size (as you describe happening). Inspect the script and find that listener, and see what it's running inside. It'll have some function(s) to calculate and render the grid, and you'd want to call those same functions in your own data-update function.
To find that listener, do a find for "resize", see what comes up.
Here's how a vanilla JS resize listener may look like:
var screenWidth = document.documentElement.clientWidth;
resizeRefresh(screenWidth);
function resizeRefresh(width) {
window.addEventListener("resize", function(){
newWidth = document.documentElement.clientWidth;
if (newWidth != width) {
width = newWidth;
// do stuff
}
}, true);
}

How to add child nodes to parent nodes without having view jump to where element is being loaded?

As I am rendering elements and appending them to a parent div, my screen keeps jumping to the bottom most element as it is being loaded rather than loading them and having the view stay at the current view. So at the beginning it should be at the top of the screen and stay there instead of jumping to the bottom and as I scroll down and it renders more elements it should stay at that spot as well whilst the rest loads.
Here is the code of what is essentially in my js file.
function loadMultipleElements(amountToLoad, url) {
var parentDiv = document.getElementById("instance");
for(var i = 0; i < amountToLoad; i++) {
var iframe = document.createElement('div')
iframe.innerHTML = '<iframe src=\"' + url + '\"></iframe>';
parentDiv.appendChild(iframe);
}
}
Then how I'm loading it in the html file with infinite scroll from jquery,
<script>
loadMultipleElements(5, "https://www.example.com");
$(window).scroll(function() {
if($(window).scrollTop() == ($(document).height()) - $(window).height()) {
loadMultipleElements(5, "https://www.example.com");
}
});
</script>
So when I run this on my localhost it will have everything render as it opens but jump to the bottom of the screen to render it then jump back to the current view. The big problem here is because of infinite scroll and how it keeps jumping to the bottom it ends up going indefinitely because it keeps jumping to the bottom triggering the jquery function.
EDIT: Plunker included though not sure how to get jquery to do infinite scrolling with plunker at the moment so right now just have a fixed load value of 10. Even already it is scrolling to the bottom as it renders more.
http://plnkr.co/edit/fUrJek3RAicHG98lUrC9?p=preview
Your problem is caused by the fact that when bing automatically focuses the search bar, your browser scrolls down to the iframe so that you can type in text.
(See a "slow-mo illustration" here.)
The only workaround I know of is to use the iframe sandbox attribute - HTML5 only! - to prevent bing from focusing the searchbar. Then when the iframe is finished loading, we reallow JavaScript. Example.
There are, however, a couple of problems with this approach.
Since it works by disabling javascript when the iframe is loading, desired javascript functionality is also disabled. (ie. no 'recent stories')
It feels incredibly hacky.
It isn't obvious what we're trying to do.
PS: Here's what W3Schools has to say about the sandbox attribute and here's a walkthrough on html5rocks.
PPS: If anyone knows of a better way to do this, I'd love to hear it.

get the height of a another web page

I'm using the following code:
$("#galleries").load("letters/index.php");
$(function(){
$('#galleries').hide().fadeIn(1500);
});
everything works fine. My problem is, I got about 8 scripts like that, and whenever I switch the content of the div, it doesn't do that smoothly, first of all, it clears the DIV and let me see that for about 0.7 seconds, after that, it loads ALL of the content within a second, and it's really disturbing my eye.
I thought about a solution, that I will get the height of the page I wanna load, and then set the DIV height to that height, and then load the info. Will it work? because, the LOAD function removes everything from the div, will it remove the height property as well?
generally, this is what im trying to achieve:
//GET TARGET'S HEIGHT
//SET #galleries TO THAT HEIGHT
$("#galleries").load("letters/index.php");
$(function(){
$('#galleries').hide().fadeIn(1500);
});
I don't know how to get the target's height and set it. But anyways, will it work? or maybe someone has another solution for me?
Thanks in advance!
You aren't using the complete callback of load() which allows you to run code after content is loaded.
Try something like this:
$(function(){
/* hide first, then load*/
$('#galleries').hide().load("letters/index.php", function(){
/* new content now exists*/
$(this).slideDown()/* or fadeIn() or any other effect*/
});
});
SlideDown is not dependent on overall height so will smoothly move content below it down

Lazy Load won't load visible images

I'm trying to use lazyload to only load images that are visible (because my site is responsive and some content is hidden with display:none to clients on a smaller screen).
Basically, lazyload works, but ONLY after I scroll the page a little.
This is the lazy load settings I'm using, and even after setting the threshold to 2000px (more than the entire page height) it still only loads images after the user scrolls the page (even 1 px).
This bug only appears in webkit browsers.
$(document).ready(function () {
$("img").lazyload({threshold : "2000", effect : "fadeIn", effectspeed: 2000,});
});
I think it could be some misbehavior of threshold parameter, but still you can manually fire the loading according to this page:
<script type="text/javascript">
$(document).ready(function () {
$("img")
.lazyload({
event: "lazyload",
effect: "fadeIn",
effectspeed: 2000
})
.trigger("lazyload");
});
</script>
but if you want to load all images on ready, why need lazyload at all? You could just use $.animate.
Just add this after .lazyload() and it will trigger scroll and show images
$(window).trigger('scroll');
You need to set width and height for you images.
If width and height are not set jQuery will report images invisible in Webkit browsers on document.load event. When skip_invisible is true Lazy Load will ignore the images, meaning it wont try to figure out whether image should be loaded or not. They will load first time you scroll.
If you set skip_invisible is false plugin will try to figure out should images be loaded. However since you do not have width and height set all images will be size of 0x0 or 1x1. Because of this all images are in viewport (because of their size) when plugin kicks in. Because images are in viewport Lazy Load will instruct to load them all.
In short: Add width and height to images. Lazy Load wont work properly without them.
I'm not sure when this got added, but you can manually fire the 'appear' event to some or all (depending on the css selector) appear:
$("img.lazy").trigger('appear');
Got this from here: http://yuji.wordpress.com/2014/05/14/force-jquery-lazyload-to-appear/
I had the same issue. They are in a scrolling div, but would only load after an initial scroll.
Using 'appear' will show them all, unless you limit it. In my case, I only wanted to show the first 3 on load. The rest of them lazy load as usual.
$("img.lazy:lt(3)").trigger('appear');
Try to pass additional parameter.
skip_invisible : false
This parameter is true by default, so it seems your images are not visible when plugin starts it's job. It could happens when you are using any preloader on your website.
I had the same problem, and found a solution for this.
Please note that my images were placed inside of a div that is populated via an ajax call.
Just change a line of code inside the lazyload sources (lines 147-150) of version 1.8.4:
/* Force initial check if images should appear. */
$(document).ready(function() {
update();
});
instead of
/* Force initial check if images should appear. */
$(window).load(function() {
update();
});
Or eventually add the call to "update()" to any other needed event.
I had a similar issue where the images wouldn't load after a ajax call until I scrolled (even if I just scrolled 1px it would load). I found I needed to add a height and width to my images like Mika Tuupola said. My images were loaded dynamically, were different image sizes and loaded from a foreach loop. I added generic width and height attribute to the image tag then after the lazyload loads the image I removed the attributes so it would show the correct image size.
<img class="lazy" src="img/placeholder.gif" data-original="img/image.gif" width="1000" height="600">
$('img.lazy').lazyload({
skip_invisible: false
}).removeClass('lazy').removeAttr('width').removeAttr('height');
I had the same problem with hidden elements, is a simple workaround but it works. When I click on the page, I triggering scroll event to force lazyload script. You can do the same thing with the event resize
$(document).ready(function () {
$("img").lazyload({
event: "lazyload",
effect: "fadeIn",
effectspeed: 2000
});
$(window).resize(function () {
$(this).trigger("scroll");
});
});
In short: Add width and height to images. Lazy Load wont work properly without them.
You should be loaded in advance placeholder;Like this:
<img src="./images/grey.gif" alt="" style="display:none">
And then
$("img.lazy").lazyload({placeholder : "images/grey.gif"});
If you set the width of the image to 100%,this will provide a width and height.
This solved my problem.
This is working solution, but in is not very good for some reason:
$("img").lazyload({
/* Image loaded callback function */
load: function() {
$(window).trigger('scroll');
}
});
Every time lazyload plugin load the picture, this function will be called and window trigger 'scroll' will be emulated, so it is a solution for me
Increase the failure_limit.
After scrolling page plugin loops though unloaded images. Loop checks if image has become visible. By default loop is stopped when first image outside viewport is found. This is based on following assumption. Order of images on page is same as order of images in HTML code. With some layouts assumption this might be wrong.
Setting failure_limit to 10 causes plugin to stop searching for images to load after finding 10 images below the fold.
I was dealing with the same issue and I noticed that this problem only occurs when images are placed inside a div that is initially hidden (ie. display: none;)

Getting the height of a div after setting it to auto in IE

I'm writing some JavaScript that changes the size of some content. To do this I need to know the size of a div within my content. If I have the following html:
<div id="wrapper">
... other stuff ...
<div id="inner" style="height:400px">Some text in here</div>
... other stuff ...
</div>
And the following JavaScript:
$('#inner').height('auto');
var height = $("#wrapper").height();
In FireFox and Chrome the height variable increases as the inner div expands to fit all the text. In IE this stays the same. I guess it doesn't redraw the div straight away. Anybody know how to get the new correct height in IE?
Cheers
It the problem is that the element doesn't redraw right away, then you need to measure the height asynchronously - set a 0-millisecond timeout to measure it and continue execution.
Try it this way:
$(function() {
$('#inner').height('auto');
var height = $("#wrapper").height();
});
Wrapping it in $(function() { }); makes it wait for the DOM to render before running the script. It's probably a good idea to put anything that needs access to the DOM immediately after render inside that function.

Categories