Call jquery function only when window width gets resized - javascript

I have a function responsive that changes behaviour of certain elements on my website, including hiding popups etc. I call it in 2 cases:
$(document).ready(responsive);
$(window).resize(responsive);
The problem occurs on android chrome, as the virtual keyboard actually changes the height of the screen, and triggers responsive function, which closes my popups (some of them have text fields, making it impossible to type).
How can I prevent this from happening? I read somewhere a good point that android virtual keyboard only changes height of the screen, not a width, so I assume it would be a good idea to compare width before and after resize. So I created this function to compare the widths before and after and run resize() if width is different, but it doesn't work as expected, and console logs show different document widths even though I only changed the height of the screen (using chrome developer tools).
Any idea what went wrong or how can I prevent function responsive being launched on height change?
function resizeWidth() {
var existingWidth = $(document).width();
$(window).resize(function() {
var newWidth = $(document).width();
if (existingWidth != newWidth) {
$(window).resize(responsive);
console.log(existingWidth);
console.log(newWidth);
};
});
};
$(window).resize(resizeWidth);

Firstly you are attaching a handler to the resize event multiple times. One on load, then another every time the resize happens and resizeWidth is called. You should remove the handler within that function. Also, I guess you just want to call the responsive() function, not attach yet another resize handler when the width changes.
The main issue you have is that the scope of existingWidth is not low enough for it to be seen over multiple events. You could make it global, although that is generally considered bad practice. Instead you could use a data attribute, like this:
function resizeWidth() {
var existingWidth = $(document).data('resize-width');
var newWidth = $(document).width();
if (existingWidth != newWidth) {
responsive();
$(document).data('resize-width', newWidth);
};
};
$(window).resize(resizeWidth);

Related

Trigger jQuery function at specific different browser widths

So I have this jQuery function that adds margin-top to an element based on the height of another element.
I'm trying to have this function trigger again on window resizes. (Preferably 1200px, 991px, 768px, 500px breakpoints)
If there is a good solution that allows the function to trigger with any browser resize, even better. I just need to make sure this wont cause "lag" or "slowness" due to the function triggering 100 times during a resize event for example.
Here is a codepenn with my current function:
http://codepen.io/bruno-gomes/pen/vgRbBB
Code:
jQuery(document).ready(function($) {
(function() {
var navBarHeight = $('.header').height();
$('.content').css('margin-top', navBarHeight);
})();
});
The idea is that I want the fixed header to not cover the content, and the size of the header will vary depending on the width of the browser. This becomes an issue when user resizes browser because the function is only triggering once on load.
I have the IIFE setup like that because it's a Joomla site and they don't work properly otherwise by the way.
You can use .resize() for that
Ok seems like this approach solved all my problems ^.^
jQuery(document).ready(function($) {
var height = $('.header').height();
resizeHeader(height);
$(window).resize(function() {
var height = $('.header').height();
resizeHeader(height);
});
function resizeHeader(height) {
$('.content').css('margin-top', height);
}
});

$(window).resize() executes when scrolling on mobile devices

For example:
HTML
<div><p>A lot of text that goes off the page so you have to scroll down.........</p></div>
JavaScript
$(window).resize(function(){
$("div").append("<p>appended</p>");
});
This works and appends the paragraph as expected on resize, but it is also appended when I scroll down. This means when I get to the end of the original text there is about 20 appended paragraphs.
This is only happening on mobile devices (so far I've checked Chrome, Safari and Firefox), not on desktop browsers.
Is there a way to stop this happening and have the paragraph appended only when the window (that you see) is resized?
Or maybe only have the code within the resize execute every so often?
Thanks.
The problem with mobile devices is that they have the browser toolbars that are hidden when you scroll and this leads to screen change (activates the resize event) and this means that you have to make some validations to your code and detect why was the resize event fired.
One way I have used is by saving the window width and checking if the correct window width is the same or changed. If it changes then it means that the append should happen (in your case).
var dwidth = $(window).width();
$(window).resize(function(){
var wwidth = $(window).width();
if(dwidth!==wwidth){
dwidth = $(window).width();
console.log('Width changed');
}
});

JQuery - Test window has been resizes over a threshold

hope you can help
My current project requires me to recall a set of functions on window resize so that I can keep the responsive nature correct. However the code I am using is rather twitchy as it calls the functions even if the window is resized by 1px.
I am relatively new to jQuery but learning more and more every day, but this is something I'm struggling to find a way to do.
In an ideal world I would like to call the functions when the window has been resized over a breaking point at anytime, for example:
say the breaking point is 500px, the initial load size is 400px the user resizes to 600px, so over the threshold so call the functions again.
It would also need to work in reverse... so window (or load) size 600px, breaking point 500px, resize to 400px call functions.
Here's the code I'm currently:
var windowWidth = $(window).width();
var resizing = !1;
$(window).resize(function(a) {
!1 !== resizing && clearTimeout(resizing);
resizing = setTimeout(doResize, 200);
});
function doResize() {
call_these_functions();
}
Cheers for the help guys
Thanks for the reply Zze
I am using something similar to what you've put, but I have it based within the start of my functions to filter what each thing does based on the window size. My problem is that these are getting called far too often and causing issues / twitchy behaviour.
For example I'm having issues on a tablet I'm testing on, when you scroll down, the scrollbar that appears on the right seems to trigger the window resize... causing functions to be called again that automatically accordion up or .hide() elements to their initial loaded state.
So my thinking is if I can test it's actually broken a set threshold rather than just what size the window is then it will be far more reliable.
There are some really handy jQuery functions available and it looks like you are very close to cracking this yourself. Hope this helps though.
$(window).resize(ResizeCode); // called on window resize
$(document).ready(function(e) { ResizeCode(); }); // called once document is ready to resize content immediatly
function ResizeCode()
{
if ($(window).width() < 500){
//insertCode
}
else if($(window).width() >= 500){
//insertCode
}
}
Update
If we are looking to 'restrict' the call time of this function, then you could add an interval which updates a bool every time it ticks, and then check this bool in the previous code:
var ready = true;
setInterval(function(){ready = true;}, 3000);
function ResizeCode()
{
if (ready)
{
// run code
ready = false;
}
}
But i would suggest storing the width and height of the window in a var and then comparing the current window with the var when the window is resized, that way you can tell if the window has actually been resized over 'x' amount or if it is that weird bug you've found.
Looks like i've found a solution that's going to do what i need with a little work (fingers crossed as i'm currently working on it), from http://xoxco.com/projects/code/breakpoints/
Thanks for the help Zze

automatically detect web browser window width change?

i know that you with $(window).width() can get the size of the web browser.
i want to detect when the user change the size of his web browser so i could readjust the columns width. is there a way to automatically detect this or do i have to use setTimeinterval to loop and see if it has changed?
Try the resize event
$(window).resize(function() {
console.log('window was resized');
});
Writing this down cause somehow none of these answers give the modern best-practices way of doing this:
window.addEventListener("resize", function(event) {
console.log(document.body.clientWidth + ' wide by ' + document.body.clientHeight+' high');
})
The JavaScript event is named window.onresize.
The JQuery binding is named .resize()
In MDN they give a really good Javascript standalone code:
window.onresize = resize;
function resize()
{
alert("resize event detected!");
}
If you need just this kind of functionality I would recommend to go for it.
You might want to use debounce :
https://davidwalsh.name/javascript-debounce-function
Otherwise the
window.addEventListener("resize")
Will fire the whole time as the window resize is in progress.
Which will tax your CPU overhead.
Something to keep in mind- in IE, at least, resize events bubble, and positioned elements and the document body can fire independent resize events.
Also, IE fires a continuous stream of 'resize' events when the window or element is resized by dragging. The other browsers wait for the mouseup to fire.
IE is a big enough player that it is useful to have an intermediate handler that fields resize events- even if you branch only IE clients to it.
The ie handler sets a short timeout(100-200 msec)before calling the 'real' resize handler. If the same function is called again before the timeout, it is either a bubblng event or the window is being dragged to a new size, so clear the timeout and set it again.
Here's a little piece of code I put together for the same thing.
(function () {
var width = window.innerWidth;
window.addEventListener('resize', function () {
if (window.innerWidth !== width) {
window.location.reload(true);
}
});
})();
I use
media="only screen and (min-width: 750px)" href="... css file for wide windows"
media="only screen and (max-width: 751px)" href="...css file for mobiles"
When I move the right windows border left and right to increase and decrease my window size, my web browser will automatically switch from the wide window to the mobile. I do not have to include any Javascript code to detect window width. This works for Chrome, Firefox and Internet Explorer on both Windows and Macintosh computers.

A bit of problem with implementing a modal dialog

I am developing a modal dialog as a part of a web application. There is one thing that's been of a puzzle to me. Please watch a movie clip that I just uploded at http://inter.freetzi.com/example/. I feel strongly that I have to accompany my question with a video because this is the case when it's better to see once, than to hear 100 times.
(It could be vertical scrolling, or both vertical and horizontal at the same time. But I am using horizontal scrolling in my example, so watch for it.)
Here's about my question:
Width of the transparent mask affects the width of the page itself. But in Opera, for exemple, every time the window gets resized, the page gets width that is at most close to 'true'. While in IE, once the transparent mask has affected the width, afterwards the page remembers it and stays with it. What is the problem and how to settle it? How to make IE behave the way Opera does?
In my project, I do the following:
//curViewpointW and curViewpointH are current width and height of the viewpoint (current is meant to be the moment of the resize event)
oMask.style.width = curViewpointW + 'px';
oMask.style.height = curViewpointH + 'px';
var pageWH = getPageWH(); //getPageWH() is a function that gets current width and height of the page (with scrolling if there is any)
var curPageW = pageWH[0];
var curPageH = pageWH[1];
if (curPageW > curViewpointW) {
oMask.style.width = curPageW + 'px';
}
if (curPageH > curViewpointH) {
oMask.style.height = curPageH + 'px';
}
But IE ignores that somehow...
P.S. It's jQuery in my example, so many of you may have used its dialog before.
Have you looked into setting an onresize event handler that will adjust your mask dimensions when the window is resized? If you are using Prototype, you can set up such a handler unobtrusively like this:
Event.observe(document.onresize ? document : window, "resize", function() {//dostuff});
courtesy of the Roberto Cosenza blog

Categories

Resources