Javascript window resize not firing onload - javascript

I'm working off a specific codepen which can be found here https://codepen.io/anon/pen/WXgvjR .. Its not mine.
Everything works perfect with it, except when i open the page on a mobile or change the browser width to be mobile size, its still displaying some items outside the browser window width ways, is there any way to detect a mobile or change in screen size and just display them going down?
The following is the resize code that is found in the codepen if that helps
$(window).resize(function(){
var margin=40;
var padding=15;
var columns=0;
var cWidth=300;
var windowWidth = $(window).width();
var overflow = false;
while(!overflow){
columns++;
var WidthTheory = ((cWidth*columns)+((columns+1)*padding)+margin);
if(WidthTheory > windowWidth)
overflow = true;
}
if(columns > 1)
columns--;
var GridWidth = ((cWidth*columns)+((columns+1)*padding)+margin);
if( GridWidth != $('#grid').width()){
$('#grid').width(GridWidth);
}
});
Any help would be greatly appreciated

Resizing using the Maximise, Minimise, or the Chrome DevTools Devices Buttons, etc. does not trigger the resize event properly (it triggers it before actually resizing, so it does not get the right size).
For the mobile page load, put the same code from the window resize function into the document ready function as well (I would recommend making it a function and then call the function in both to reduce duplicate code):
function setDisplayBoardSize()
{
var margin=40;
var padding=15;
var columns=0;
var cWidth=300;
var windowWidth = $(window).width();
var overflow = false;
while(!overflow){
columns++;
var WidthTheory = ((cWidth*columns)+((columns+1)*padding)+margin);
if(WidthTheory > windowWidth)
overflow = true;
}
if(columns > 1)
columns--;
var GridWidth = ((cWidth*columns)+((columns+1)*padding)+margin);
if( GridWidth != $('#grid').width()){
$('#grid').width(GridWidth);
}
}
$(window).resize(function()
{
setDisplayBoardSize();
});
$(document).ready(function()
{
setDisplayBoardSize();
});
For the min-max etc. see this stackoverflow thread:
jQuery resize() using browser maximise button
This answer specifically should help:
$(window).resize(function()
{
setTimeout(function() {
setDisplayBoardSize();
}, 100);
});

Related

Alternative of position fixed using JavaScript shows weird behavior on window resize

I have CSS transform scale on the body of my page and some other elements. The position fixed CSS property doesn't work with transform property. I tried to do the same as position fixed but with JavaScript by changing the element's top/bottom value while scrolling. This requires some calculations dynamically as you load the page on different sized screens. Mine works on different screens but when I do window resize on any screen, the fixed div behaves weirdly. It disappears and reappear again. Sometimes it doesn't fixes its position on the intended scroll-y value. I have applied "scroll" and "resize" event listeners for the body/window. I had to do some initial calculations before scroll event, so some functions are under a parent function.
JAVASCRIPT
function chekon()
{
document.addEventListener('DOMContentLoaded', upme);
window.addEventListener('resize', upme);
function upme()
{
var rome = document.getElementById("out-cmnt");
var rect = rome.getBoundingClientRect();
// console.log(rect.top, rect.right, rect.bottom, rect.left);
var poss = rect.top + window.scrollY;
var koss = rect.bottom + window.scrollY; var loss = koss - poss;
var isMobile = !(navigator.userAgentData.mobile);
// event listeners
// window.addEventListener('resize', relod, false);
// function relod() { if(isMobile) { location.reload(); } }
window.addEventListener('scroll', doso, false);
window.addEventListener('resize', doso, false);
function doso()
{
lopp = document.getElementById("Web_1920__1");
hope = lopp.clientHeight;
const meme = document.body.scrollHeight;
const keke = hope/meme;
const scsc = window.scrollY;
var scmx = (document.documentElement.scrollHeight - document.documentElement.clientHeight);
console.log("meme scroll-height = ", meme); console.log("scsc scroll-y = ", scsc);
console.log("scmx max-scroll-y = ", scmx);
var innr = window.innerHeight; console.log("innr inner-height = ", innr);
var scbb = scmx - scsc; var finn = scsc * keke; var nunn = scbb * keke;
if (window.matchMedia("(min-width: 765px)").matches)
{
var finn = scsc * keke * 1.087;
var nunn = scbb * keke * 1.087;
}
var noss = poss - innr + loss;
if(scsc > noss && window.matchMedia("(min-width: 765px)").matches && isMobile)
{
var xoxo = nunn;
document.getElementById("out-cmnt").style.top = "auto";
document.getElementById("out-cmnt").style.bottom = xoxo + "px";
}
if(scsc < noss)
{
document.getElementById("out-cmnt").style.top = "7074px";
}
if(nunn < 100 && isMobile)
{
document.getElementById("last-dab").style.visibility = "hidden";
}
if(nunn > 100 && isMobile)
{
document.getElementById("last-dab").style.visibility = "visible";
}
} }
}
chekon();
Function upme() and doso() is under function chekon() there. The upme() has 2 event listeners and doso() has also 2 event listeners with resize in common. I checked that if doso() resize isn't applied, the upme() resize event listener has no effect on doso() even though doso() is under upme() function. I though, maybe there is overlapping. But seems like fine to me. Is there something messed up in my code that is responsible for the window resize action? The "Web_1920__1" is for getting the total height of the page. The "out-cmnt" is flickering and showing up at wrong place after stopping window resize action for the browser. Then when I start scrolling again the element should get back at its intended position again. But no, staying at wrong position. A reload only fixes the problem for now. Funny thing is, I can't reproduce the wrong position even when the resize is down to at the same window size that showed the problem before. So I think Chrome is showing the problem at random window resizes. Is it browser bug or mine? Help me out please.
You can ignore the variables and calculations. Just care more for the structure, functions and event-listeners like any wrong declarations. Please help me to understand the problem.

Scroll firing too many times and crashing chrome and opera

I wrote a program in which you drag my custom scroll bar and page scrolls accordingly, everything works fine, however while testing it I discovered that if the page is too big 20 000 pixels and you do a large scroll it will crash chrome and opera.
This is caused by window.scroll(0, whereto1); being fired too many times on drag. when i comment this line of code everything works on the large scroll obviously, except for the functionality of scrolling page while dragging.
Below is the relevant code, if anyone has any good idea on how to do this without crashing the browser on large pages let me know. Thank you very much for your time.
var $dragging = null;
var pageheight1 = $( document ).height();
$(document.body).on("mousemove", function(e) {
if ($dragging) {
var wrap = jQuery('.pvs_inner_fixedbar');
wrapoffset = wrap.offset();
wrapbottomborder = ( wrapoffset.top + wrap.height() ) - jQuery('.pvs_scroll_marker').height();
var pos = e.pageY;
if(pos < wrapoffset.top){
pos = wrapoffset.top;
}
if(pos > wrapbottomborder){
pos = wrapbottomborder;
}
$dragging.offset({
top: pos
});
var ratio1 = pageheight1 / 400;
var whereto1 = Math.round((pos - wrapoffset.top) * ratio1) - 100;
window.scroll(0, whereto1); // FIRES TOO MANY TIMES :((((
}
});
$(document.body).on("mousedown", ".pvs_scroll_marker", function (e) {
$dragging = $(e.target);
});
$(document.body).on("mouseup", function (e) {
$dragging = null;
});
You can throttle calls to window.scroll() called from mousemove event handler
https://remysharp.com/2010/07/21/throttling-function-calls

jQuery auto-run when screen rotating

I'm kinda new to jQuery and JS and i'm trying to make a text-size adjustable to the screen width on a mobile site
I search the web for an answer and came up with this solution
(function($) {
$.fn.textfill = function(maxFontSize) {
maxFontSize = parseInt(maxFontSize, 10);
return this.each(function(){
var ourText = $("span", this),
parent = ourText.parent(),
maxHeight = parent.height(),
maxWidth = parent.width(),
fontSize = parseInt(ourText.css("fontSize"), 10),
multiplier = maxWidth/ourText.width(),
newSize = (fontSize*(multiplier-0.1)),
textHeight = ourText.height();
if(newSize > 35){
ourText.css("fontSize",35);
}
else{
ourText.css(
"fontSize",
(maxFontSize > 0 && newSize > maxFontSize) ?
maxFontSize :
newSize
);
}
});
};
})(jQuery);
$(document).ready(function() {
$('.jtextfill').textfill({ maxFontPixels: 36 });
});
but then it was only when the page first reloads and not on windows resizes, so I entered it all into a function and added
$(document).ready(function () {
resizeTextHeb();
$(window).resize(function() {
resizeTextHeb();
});
});
but now on the iPhone/iPad/Android etc. it doesnt reload the function when the screen rotates.
doesnt the screen rotation acts as a window resize? what can I do to make it work?
thanks.
thanks
You may use media queries for that, without using js.
your function name was "resizeTextHeb()" on the main question, any function name issues!?
i suggest u to use google chrome js console for error reports or the error console on the FF browser. , anyway, if it does alert u, so the main issue is with ur function, not the orientation method.

Javascript dialog is programmed to move when the page scrolls, but it flickers. Can this be fixed?

I've written some jQuery code to display a box with data in the corner of the users' web browser. I'm using the .scroll event to make the box stay in the corner as the user scrolls up and down the page. Let me emphasize that I am not using jquery-ui dialog.
The only problem is that the box flickers as the page scrolls. I'm afraid that there will be no cross-browser solution to this problem as the different browsers seem to behave differently with scrolling. Barring a cross-browser solution, an IE solution would be nice (My web application is designed to be used by a specific group of about 100 users in my organization.)
Here are snippets of the relative code:
ExternalScroll: function () {
LittleBlackBook.setPosition();
}
setPosition: function () {
var scrollPosition = $(self).scrollTop();
var cssTop = LittleBlackBookStatic.determineCssTop(this.height, this.isTop, this.vOffset, scrollPosition);
var cssHeight = LittleBlackBookStatic.determineCssHeight(this.height);
var cssLeft = LittleBlackBookStatic.determineCssLeft(this.width, this.isLeft, this.hOffset);
var cssWidth = LittleBlackBookStatic.determineCssWidth(this.width);
this.jQueryObj.css('top', cssTop);
this.jQueryObj.css('height', cssHeight);
this.jQueryObj.css('left', cssLeft);
this.jQueryObj.css('width', cssWidth);
}
var LittleBlackBookStatic = {
determineCssTop: function (height, isTop, vOffset, vScroll) {
var windowHeight = $(self).height();
var scrollPosition = $(self).scrollTop();
var newModalTop = isTop ? vOffset + vScroll : windowHeight - height + vScroll - vOffset;
return newModalTop + 'px';
},
determineCssHeight: function (height) {
return height + 'px';
},
determineCssLeft: function (width, isLeft, hOffset) {
var windowWidth = $(self).width();
var newModalLeft = isLeft ? hOffset : windowWidth - width - hOffset;
return newModalLeft + 'px';
},
determineCssWidth: function (width) {
return width + 'px';
}
} // end LittleBlackBookStatic
I'm using jQuery to look up the scroll position as the page scrolls and change the CSS.
Is there a better way; a way that will make it scroll without flickering? If no, then why not?
You should use fixed positioning for that box instead instead of animating it to keep it in the corner.
You'll use less javascript and avoid flickering that comes with animation.

Auto-detect a screen resolution and change browser zoom with Javascript?

How do I auto-detect a screen resolution and change browser zoom with Javascript?
I was thinking of something more like this:
I've got the following code:
#warp with width: 3300% and a mask with width: 100%; and then, each .item has width: 3.030303% — with overflow hidden, otherwise it couldn't work as I want.
My point is: I've done this for at least 1280px wide screens.
What I want is if someone can write code that I could use toswitch the CSS file once viewed on a <1280px screen — them, I could do something like:
.item img { width: 80%; } and then, the result would be the same as "browser zoom out".
If you mean change the native browser zoom triggered by CTRL +/- then this isn't possible. You can adjust CSS properties/apply stylesheets but you cannot affect native browser controls. There are in fact CSS only options here depending on your target audience (and their browser choice) through the use of media queries, a couple of examples here and here. If these are not suitable then you can do various things with JavaScript to detect screen width/height and adjust accordingly.
Auto-detect a screen resolution
See this SO question
change browser zoom with javascript
This is not possible. See this SO question.
This will help to detect browser zoom tested on all browser
<script>
window.utility = function(utility){
utility.screen = {
rtime : new Date(1, 1, 2000, 12,00,00),
timeout : false,
delta : 200
};
utility.getBrowser = function(){
var $b = $.browser;
$.extend(utility.screen,$.browser);
utility.screen.isZoomed = false;
var screen = utility.screen;
screen.zoomf = screen.zoom = 1;
screen.width = window.screen.width;
screen.height = window.screen.height;
if($b.mozilla){ //FOR MOZILLA
screen.isZoomed = window.matchMedia('(max--moz-device-pixel-ratio:0.99), (min--moz-device-pixel-ratio:1.01)').matches;
} else {
if($b.chrome){ //FOR CHROME
screen.zoom = (window.outerWidth - 8) / window.innerWidth;
screen.isZoomed = (screen.zoom < .98 || screen.zoom > 1.02)
} else if($b.msie){//FOR IE7,IE8,IE9
var _screen = document.frames.screen;
screen.zoom = ((((_screen.deviceXDPI / _screen.systemXDPI) * 100 + 0.9).toFixed())/100);
screen.isZoomed = (screen.zoom < .98 || screen.zoom > 1.02);
if(screen.isZoomed) screen.zoomf = screen.zoom;
screen.width = window.screen.width*screen.zoomf;
screen.height = window.screen.height*screen.zoomf;
}
}
return utility.screen;
};
window.onresize = function(e){
utility.screen.rtime = new Date();
if (utility.screen.timeout === false) {
utility.screen.timeout = true;
setTimeout(window.resizeend, utility.screen.delta);
}
};
window.resizeend = function() {
if (new Date() - utility.screen.rtime < utility.screen.delta) {
setTimeout(window.resizeend, utility.screen.delta);
} else {
utility.screen.timeout = false;
utility.screen = utility.getBrowser();
if(window.onresizeend) window.onresizeend (utility.screen);
if(utility.onResize) utility.onResize(utility.screen);
}
};
window.onresizeend = function(screen){
if(screen.isZoomed)
$('body').text('zoom is not 100%');
else{
$('body').text('zoom is 100% & browser resolution is'+[screen.width+'X'+screen.height]);
}
};
$(document).ready(function(){
window.onresize();
});
return utility;
}({});
</script>
Demo
RE: Auto-detect a screen resolution and change browser zoom with Javascript?
The question is perfectly possible and is in effect at our website here:
www.noteswithwings.com
JS detects the screen width and zooms out or in a little to fit the content on to the screen.
Further, if the user resizes the window the zoom is triggered.
This actually helps fit content on to tablet sized screens and screens as small as the iphone without adding extra stylesheets or having to detect an OS/ Browser..
var oldZoom = $(window).width();
var windowWidth = $(window).width();
check_window_size(windowWidth,1,bsr,bsr_ver);
$(window).resize(function() {
var windowWidthnow = $(window).width();
check_window_size(windowWidthnow,2,bsr,bsr_ver);
});
function check_window_size(size,init_var,bsr,bsr_ver)
{
/* Develop for resizing page to avoid grey border!
Page layout 1265px wide.
On page resize shift layout to keep central, zoom BG-img to fill screen
Zoom content down for smaller screens by 5% to keep content flow!
*/
//change this var for screen width to work with, in this case our site is built at 1265
var wdth = 1265;
//Change this variable for minimum screen;
var smallest_width=1120;
var varZoom= $(window).width()/wdth;
var s_size = $(window).width();
var scale_smaller;
var center = (s_size-wdth)/2;
var its_ie=false;
if(size<=smallest_width)
{
$("#old_browser").css("width","50%").css({"height":"40px","left": center+"px"});
if(!check_for_object(false,"moved_pages"))
{
if(center<-110)//margin width!
{
if(!its_ie)
$("#scroller").css("zoom",0.95);
$("#footer").css("zoom",0.9).css("left",120+"px");
$(".colmask").css("left",-110+"px");
if(check_for_object(false,"move_menu_loggedin"))
$("#move_menu_loggedin").css("right","110px");
if(check_for_object(false,"login_div"))
$("#login_div").css("left","-80px");
return;
}
$("#move_menu_loggedin").css("left","-"+center+"px");
$("#scroll").css("zoom","normal");
$(".colmask").css("left",center+"px");
}
else
{
/*Only pages that you do not want to move the colmask for!*/
$("#scroller").css("zoom",0.90);//.css("left","-50px");;
$("#footer").css("zoom","normal");
}
}
else
{
if(size>wdth)
$("#background").css("zoom",varZoom);
$("#scroller").css("zoom","normal");
$("#footer").css({"zoom":"normal","left":0});
if(!check_for_object(false,"moved_pages"))
{
$(".colmask").css("left",center+"px");
$(".colmask").css("zoom","normal");
var movelog = -center;
if(check_for_object(false,"move_menu_loggedin"))
$("#move_menu_loggedin").css("right",movelog +"px");
if(check_for_object(false,"login_div"))
$("#login_div").css("left","80px");
}
else
{
$(".colmask").css("zoom","normal");
}
}
}
-- check_window_size(windowWidth,1,bsr,bsr_ver); bsr & bsr_ver are detected using a php class.
-- #old_browser is a div containing information if you have an old web browser.
-- #background is a fixed image 100x100% of the screen.
As you can see we also move a few items which were not in the containing div scope.
Colmask is the containing div for most of the pages content (For us that sits underneath the header which is why we move some items manually)
Hope the code snippet can help someone else achieve this.

Categories