chrome mobile, jquery .ready() not firing when expected - javascript

I am working on an app for desktop/mobile. The jQuery $(document).ready(); is definitely firing, which is why the app works. However, in the Chrome mobile browser, one particular function (to add some dynamic CSS to one element to place it correctly) is not firing correctly, and thus not updating the CSS when the page loads. The function fires normally and updates the CSS in the desktop browser. Here is the code:
$(document).ready(function() {
function placeBook() {
var h = $('#header').css('height');
$('#button').css('height', h);
$('#button').css('line-height', h);
}
placeBook();
$(window).resize(function() {
placeBook();
});
});
The function placeBook() is not updating the CSS of the #button div on the first load of the page. However, the function fires normally on resize of the window, as specified in the code. It only fails on the mobile browser at the initial load of the page. See these SS's:
First load in desktop (FF responsive design view):
First load in mobile (Chrome):
As you can see, the idea is that the book icon is to be centered vertically in the header. Of course, any help is appreciated.
Here is the HTML/CSS:
<div id='header'>
<div id='button'></div>
</div>
#header {
position: fixed;
top: 0;
width: 100%;
font-size: 120%;
text-align: center;
}
#button {
position: absolute;
top: 0;
left: 0;
padding: 0 1%;
}

Had a similar problem in Chrome: css is not being applied to dom, but when updated in console or styles are modified starts applying.
The problem was in sending incorrect mime type in headers of css files. This is chrome-specific peculiarity, because FF was more forgiving. Sending "text/css" fixed problem.
Hope it helps.

As per this answer:
window.load doesn't fire always on chrome?
It seems that it isn't safe to use $(window).load(); on chrome, especially when it comes to DOM modifications. Instead use $(document).ready();! I've created a simple fiddle to confirm that load isn't always firing in chrome: http://jsfiddle.net/KvD6G/
Furthermore, instead of fixing this with javascript try doing it with css by applying the following styles:
#button {
...
display:inline-block;
vertical-align:middle;
...
}

I think you have to place your placebook() function in the global scope, outside of doc ready handler:
function placeBook() {
var h = $('#header').css('height');
$('#button').css({
'height': h,
'line-height': h
});
}
$(window).load(function() {
placeBook();
$(window).resize(function() {
placeBook();
}).resize(); //<----invokes the resize function immediately
});
Although you have not mentioned your doc ready handler:
function placeBook() {
var h = $('#header').css('height');
$('#button').css({
'height': h,
'line-height': h
});
}
$(function(){ //<------------------doc ready handler
$(window).load(function() {
placeBook();
$(window).resize(function() {
placeBook();
}).resize(); //<----invokes the resize function immediately
});
});

Related

Javascript randomly not loading

I've got a page I'm coding, and it's supposed to run this Javascript on every page load. The problem is, it seems to load completely randomly. Sometimes it runs, sometimes it just doesn't. Every reload seems totally random on whether it will work or not. This is very frustrating as I can't imagine it's an issue with the code at this point.
function randombg() {
var random = Math.floor(Math.random() * 6) + 0;
var bigSize = ["url('http://lh4.googleusercontent.com/-dsFg9OnYo5Q/T0hK7b0-xoI/AAAAAAAABL4/9_CPzXBCMfw/s800/animated%2520blue%2520stars.gif')",
"url('https://background-tiles.com/overview/blue/patterns/large/1026.gif')",
"url('https://78.media.tumblr.com/395d407e0762d7041cbe0197e3ea288c/tumblr_o3fxwiIAq61v8fqfeo1_540.gif')",
"url('http://backgroundcheckall.com/wp-content/uploads/2017/12/seamless-repeating-background-gif-12.gif')",
"url('https://other00.deviantart.net/b3aa/o/2009/312/0/8/143009517_95116_animated_starfield_tile.gif')",
"url('http://backgroundcheckall.com/wp-content/uploads/2017/12/seamless-repeating-background-gif-10.gif')"
];
document.getElementById("random").style.backgroundImage = bigSize[random];
alert("Success");
}
window.onload = randombg;
window.onresize = randombg;
#random {
width: 100%;
height: 450px;
border: 1px solid black;
background-image: url('http://placehold.it/300&text=banner1');
background-position: center center;
background-size: cover;
background-repeat: no-repeat;
}
<body onload="randombg">
<div id="random"></div>
<body>
This is taken from this pen, which works flawlessly. So I'm very confused as to why it's not working consistently for me.
I'm running Chrome (67.0.3396.99) in Windows 10 (1803), and this code is being run in the extension Super Evil New Tab, which has a section for HTML, CSS, and JS.
Thank you for any feedback or advice.
EDIT: I forgot to mention that the extension seems to just stick the HTML into a body.
The simplest, non-library-dependent way to fix inconsistent JavaScript initialization execution is to change <body onload="randombg"> to just <body> and insert your JavaScript before your script tag like so:
<script src="path/to/your/js/file/here.js"></script>
<body>
<div id="random"></div>
</body>
And then in your JavaScript file, instead of using window.onload = ..., do:
// This method of attaching a function to a DOM event allows for more flexibility down the line.
window.addEventListener('load', randombg);
window.addEventListener('resize', randombg);
If you use this addEventListener way, if you choose to do more than just randombg on load and resize events, you could just do
window.addEventListener('load', () => {
randombg();
// more code to perform on load here...
});
window.addEventListener('resize', () => {
randombg();
// more code to perform on window resize here...
});

Using Jquery, how do I find pixel value of a property's percentage and add it to a different property?

I'm new to jquery and I'm having some trouble with it.
.pageimage {
width:80%;
height:60%;
margin:0 auto;
background:#0FF;
position:absolute;
left:;
top:20%;
}
Using jquery, I'm trying to find the pixel value of 'top', subtract 50% from that value, and then place that value on the 'left' property.
Also, does anyone know how to rerun this script after the browser window has been resized?
Help is greatly appreciated.
You can easily do this, using the .css() method creatively. If you get the .css("top") of an element, it is returned in px, so you have to replace("px","") to be able to use the numeric value, then divide by 2, then add the "px" at the end again.
Wrap this up in a function and call it when your page loads. Then add a $window.resize() handler to run the function every time the window is resized after it's loaded.
Here's a full example:
function updatePageImageLeft() {
var calculatedLeft = $(".pageimage").css("top").replace("px", "") / 2 + "px";
// console.log(calculatedLeft);
$(".pageimage").css("left", calculatedLeft);
}
// Called when the page loads
updatePageImageLeft();
// Page has been resized, call it again
$(window).resize(function() {
updatePageImageLeft();
});
.pageimage {
width: 80%;
height: 60%;
margin: 0 auto;
background: #0FF;
position: absolute;
/*left: ;*/
top: 20%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pageimage"></div>
Note: You might also want looking into the CSS calc() function, as it could help you avoid writing any Javascript/jQuery code in the first place (especially if you combine it with CSS custom properties).
To get the Value of "top" you can youse the function css.
var top = $(".pageimage").css("top");
$(".pageimage").css("left",parseInt(top)* 0.5);
to rerun the script after the window has been resized use:
$(window).resize(function() {
//place Code here
}
Link to jsfiddle
Edit
use parseInt to get the int-Value of top

How to use .load to .prepend content without page refresh?

I'm trying to use jQuery to only load certain content if the viewport is above a specified width.
This works, but not quite right. Check out the JsFiddle link at the bottom for a working demo.
Here's what I have so far;
If the viewport is below 500px #wrapper is hidden with a media query.
Above 500px #wrapper is set to visibility: visible;
jQuery is looking for element.is(':visible'). When this happens jQuery loads the image.
Resizing the browser window activates the media query, but not the jQuery.
The jQuery only fires on a page refresh.
I've tried using $( window ).resize(function() but this fires every time the viewport changes size, duplicating the content.
Is there a way to activate jQuery without a page refresh?
The ideal solution would be;
up to 500px load nothing,
when the viewport is resized above 500px load the jQuery.
If the viewport is resized below 500px unload the jQuery content.
HTML
<p>CSS hides <strong>#wrapper</strong> if viewport is below 500 pixels.</p>
<div id="wrapper">
<p>jQuery checks CSS to see if <strong>#wrapper</strong> is visible and loads image on page refresh.</p>
<p>I'm looking for a way to run this function without needing to refresh the page. I've looked into using (resize) function, but this duplicate the content.</p>
CSS
#wrapper {
visibility: none;
display: none;
}
#media only screen and (min-width: 500px){
#wrapper {
visibility: visible;
display: block;
}}
JQuery
$(function() {
var element = $(this).find('#wrapper');
if (element.is(':visible')) {
$('#wrapper').prepend('<img src="http://cache.desktopnexus.com/thumbseg/1134/1134934-bigthumbnail.jpg" alt="Demo image">');
}
JsFiddle link:
https://jsfiddle.net/tu60wbbu/13/
You can use window.matchMedia() instead of $(window).resize() to have your javascript respond to a media query match in your CSS.
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
It's fairly well supported across browsers.
http://caniuse.com/#search=matchmedia
If you need to support IE 9 or lower, you might have to fall back to using $(window).resize() for those browsers.
Here is the code for my comment:
$(function() {
var large = false;
var barrier = 1000;
$( window ).resize(function() {
if(!large && $(window).width() > barrier) {
large = true;
$('#wrapper').prepend('<img src="http://cache.desktopnexus.com/thumbseg/1134/1134934-bigthumbnail.jpg" alt="Demo image">');
} else if(large && $(window).width() < barrier) {
large = false;
$('#wrapper img').remove();
}
});
});
Working Fiddle: https://jsfiddle.net/tu60wbbu/14/
I used 1000px as the barrier in the demo.
You should initialize large properly by the window width on load. For demo purposes i used false as initial value.
Sorry for the long time, I was at vaccation :-)

Event when the user changes font size in browser?

I need to get informed when the user changes the font size in it's browser.
I need it to reposition some elements which have to be relative in one dimension to an anchor inside a text.
So far i haven't found anything and i'm a bit worried that it's not possible. In this case it should be possible to emulate it with a hidden div and some text inside and a script polling for changes of it's width. But i hope someone has a more elegant solution.
EDIT:
I implemented the polling thing like following. It's not properly tested on all Browsers but it doesn't depend on browser specific features. use it like $('body').bind('fontResize', function(){...})
$(function(){
$('body').append($('<div id="theFontResizeCaptureDiv">A<br>B<br>C</div>'));
$('#theFontResizeCaptureDiv').css({visibility: 'hidden', position: 'absolute'});
window.setInterval(function(){
var div = $('#theFontResizeCaptureDiv');
var stored = parseInt(div.attr('c_height'));
if(isNaN(stored)){ // first run
div.attr('c_height', div.innerHeight());
}else if(stored != div.innerHeight()){ // changed
div.attr('c_height', div.innerHeight());
$('body').trigger('fontResize');
}
}, 200);
});
Here's a link to an article describing different methods to detect font resizing:
http://www.alistapart.com/articles/fontresizing/
You can use idea from this file https://github.com/marcj/css-element-queries/blob/master/src/ResizeSensor.js
I've incorported it in jQuery Terminal as jQuery plugin and use div with and css:
.font {
position: absolute;
font-size: inherit;
top: 0;
left: 0;
width: 1em;
height: 1em;
}
that way if parent element, that have position: relative or absolute, change font-size the .font element will change size and trigger resizer callback.
You can use this plugin like this:
var font = $('<div class="font"> </div>').appendTo(self);
font.resizer(function() {
// font changed size
});
where self is your parent element, if you need to detect this event on body you can use 'body' instead.

html onresizeend event, or equivalent way to detect end of resize

I'm trying to detect when the onresize event ends in a browser. If I use the onresize event, in Firefox it seems to be fired only once, after the resize event ends, which is exactly what I want. But if I try in IE, the onresize event gets fired many times during the resize.
I also try the onresizeend event, advertised in MSDN. But it does not seem to get fired at all, neither in Firefox, nor in IE. I use the following code:
<html>
<head>
<script>
<!--
function doLog(message)
{
document.getElementById("log").innerHTML += "<br/>" + message;
}
function doResize()
{
doLog("plain resize");
}
function doResizeEnd()
{
doLog("resize end");
}
-->
</script>
<style>
<!--
#log {
width: 400px;
height: 600px;
overflow: auto;
border: 1px solid black;
}
-->
</style>
</head>
<body onresize="doResize();" onresizeend="doResizeEnd();">
<div id="log"/>
</body>
</html>
Any ideas why this does not work? Maybe the onresizeend event is not supported? In this case, how can I detect when the resize event has ended?
From MSDN onresizeend()
Only content editable objects can be
included in a control selection. You
can make objects content editable by
setting the contentEditable property
to true or by placing the parent
document in design mode.
That explains why it's not firing for you. I suspect you don't want to enable contentEditable, so why not set a timer.
var resizeTimer = 0;
function doResize()
{
if (resizeTimer)
clearTimeout(resizeTimer);
resizeTimer = setTimeout(doResizeEnd, 500);
}
It's not perfect but hopefully will be good enough.

Categories

Resources