Execute javascript code ONLY if width is higher than x pixels - javascript

I'm trying to execute a javascript function ONLY if the width is bigger than 1200pixels.
The code I need to execute works, but the check for the screen size doesn't:
window.addEventListener("resize", function(){
if (document.documentElement.clientWidth > 1203) {
<<<some other code that's working>>>
}
}, true);
All this code is in a javascript file outside the document.ready function.
EDIT: When you drag your screen window around, it isn't working like normal css queries. This is the problem. It works if you refresh your page, but if you change the width of your browser, then it doesn't adjust, it needs the reload right now.
That's my issue.

You need to add an else clause to get the behaviour you want. Otherwise the resize event will only work going one way, as you described.
window.addEventListener("resize", function(){
// fire when above 1203
if (document.documentElement.clientWidth > 1203) {
console.log('Greater!');
}
// fire when below 1203
else {
console.log('Smaller!');
}
}, true);
Here's a link to the fixed jsfiddle that planet260 wrote: http://jsfiddle.net/4dnemh2j/4/
Here's my example again: https://jsfiddle.net/9n5hmpua

The problem is the true you're passing to addEventListener.
See the useCapture section here: EventTarget.addEventListener
Events which are bubbling upward through the tree will not trigger a listener designated to use capture
So you want:
window.addEventListener("resize", function(){
if (document.documentElement.clientWidth > 1203) {
<<<some other code that's working>>>
}
}, false); <----change here

You can use jQuery to achieve this
$( window ).resize(function() {
console.log($( window ).width());
var windowwidth = $( window ).width();
if (windowwidth > 500) {
console.log("Greater than 500");
/*Do your work here*/
}
});

Related

How to detect window width changes without resizing

I already looked for the .resize() jquery function but the jquery .resize() only triggers when the window is being resized, what i wanted was a trigger that shoots when the width changes for example, instead of changing the browser width the user clicks in the button to maximize and the function fails to trigger, i have a function that fires a function on resize(), is there any function that is like on("windowwidthchanges") ?
You can detect both events and just execute code when it's a width change:
var width = $(window).width();
$(window).resize(function(){
if($(this).width() != width){
width = $(this).width();
console.log(width);
}
});
I've checked Chrome, Firefox and IE11. All 3 browsers trigger the alert when the maximize button is clicked.
$(window).resize(function(){ alert("resized"); });
What, specifically, are you trying to do that this doesn't work for you?
You can move the code to a named function and call it on resize and when clicking the button.
Or, you can trigger the resize when clicking the button:
$("button").on("click", function(){
$(window).trigger("resize");
});
Examples: http://jsfiddle.net/cde7fwrb/
EDIT: I see you were talking about the browser maximise button. Oh well....

JQuery if statement not working as expecting

I'm using Bootstrap 3 and creating an if statement with JQuery to make my navbar collapse when anything on the body is clicked, but only when the browser width is less than 992px. When the browser is 992px or wider, I want this function to be ignored. My function below is working as expected, except for the fact that "test" gets logged to the console when the body is clicked on all browser widths when it should only do so when it is less than 992px. Is something wrong with my if statement below?
if ($(window).width() < 992) {
$('body').click(function() {
console.log("test");
$('.navbar-collapse').collapse('hide');
});
};
I updated my code to have the if statement inside of the function, as seen below. It still functions properly and only logs "test" to the console on the correct browser width, but I'm wondering if this is a bad way to do it as the browser will be checking its width on every click even when I don't want it to. Is that a bad way of doing things? Is it better practice to try to get the first code I posted to work?
$('body').click(function() {
if ($(window).width() < 992) {
console.log("test");
$('.navbar-collapse').collapse('hide');
};
});
The second method is the way to go. The first one will only bind the click event if the width is less than 992 when that block of code initially executes.
What if the user resizes the browser after the initial decision to bind/not bind has been made? That's why you need to check the width on every click.
If you bind your click event handler using .bind(), you can use the .resize() event to only have the handler bound when the screen is under your desired width. The .unbind() function does the job. For example:
var collapseNavbar = function() {
console.log("test");//remove when done with testing
$('.navbar-collapse').collapse('hide');
}
$(window).resize(function() {
if($(window).width() < 992) {
$('body').bind('click',collapseNavbar);
} else {
$('body').unbind('click',collapseNavbar);
}
});
This way the check for window width is only done while/after resizing, and not on every click.
The bound function can be named as you wish, just make sure it is indeed named so unbinding can work properly. As the documentation says:
By naming the handler, we can be assured that no other functions are accidentally removed.
I'm not sure if the resize event is raised when the page is loaded, though. You might need to add a little snippet to ensure the behavior is present for a browser window which starts at a width lower than 992px (i.e. if you refreshed the page after resizing, or if you're viewing it on a smartphone). Something like this should do it:
$(document).ready(function() {
if($(window).width() < 992) {
$('body').bind('click',collapseNavbar);
}
});

window.resize - Won't fire until I've manually changed the browser width

I have a little code snippet here:
$(window).resize(function() {
if ($(window).width() <= 768) {
$('.menu-item-810').click(function () {
$('.squares').slideDown(2000);
});
}
});
That says when the browsers window width is less than or equal to 768px, when you click on the element that has a class of .menu-item-810, slideDown the .squares element.
That is what I want, and it does work.. but only 99.8% correctly.
When the screen width is larger than 768px, the .squares element has a different jQuery effect, it fades in and out, instead of sliding. I needed it to slideDown instead, when in tablet/mobile view, so I wrote the above snippet.
Like I said, it all works, but say I've opened any browser, resized it to 768px or less width, browsed to the site and then click on .menu-item-810. Nothing happens. It's only when I then manually resize the browser again, by any amount, that the jQuery fires. So if I've just resized the browser again, and then click .menu-item-810, the .squares element slides down like expected, but only if I manually resize the browser. I thought that the jQuery would be listening from the start if I wrapped that snippet in $(document).ready() but that doesn't work either, it just has the same behavior as without.
Anyhoo, any help is as always massively appreciated. Hopefully I'm just missing something simple.
Thanks guys!
Actually, this makes no sense? The resize event handler fires thousands of times when the window is resized, and binding a click event handler inside the resize handler will get you thousands of click handlers.
Attach one single click handler, and check the windows width inside it
$('.menu-item-810').click(function () {
if ($(window).width() < 768) {
$('.squares').slideDown(2000);
}
});
Once your javascript has loaded, it needs a resize event to fire in order to trigger your code. - it doesn't know if the window has been resized prior to the handler being initialised.
Put the same snippet in your document.ready() function to do an initial check for window size:
$(document).ready(function() {
if ($(window).width() < 768) {
$('.menu-item-810').click(function () {
$('.squares').slideDown(2000);
});
}
});
In the order of your code, it is first checking the window size, and only then, if it is small, adds your event handler.
It sounds like what you want is to always call the event handler, and then change the action depending on the side.
$(window).resize(function() {
$('.menu-item-810').click(function () {
if ($(window).width() <= 768) {
$('.squares').slideDown(2000);
}
});
});
Actually, now that i think some more, you don't even need to set the handler upon resize. Just set it on document load, and check the size when it gets clicked.
$(document).ready(function() {
$('.menu-item-810').click(function () {
if ($(window).width() <= 768) {
$('.squares').slideDown(2000);
}
});
});

need an event triggered if the page has scrolled 200px down (jQuery)

I want to show and hide a piece of code if i scroll and the page is for example half way, i have tried to use window scroll but this doesnt works(no errors, clean code, different browsers, different jQuery versions), but this doesn't trigger anything, so i am looking for a better way to show and hide a div if i scrolldown.
used this to trigger an event(not working)
$(window).scroll(function(){
alert('works')
});
Try using the window.onload function (that's how they use it in jQuery examples):
window.onload = (function(){
$(window).scroll(function () {
if( $(window).scrollTop() > 200 ) {
// Display something
}
})
})

Detect when a window is resized using JavaScript ?

Is there any way with jQuery or JavaScript to trigger a function when the user ends to resize the browser window?
In other terms:
Can I detect mouse up event when user is resizing the browser window? Otherwise:
Can I detect when a window resize operation is finished?
I'm currently only able to trigger an event when the user start to resize the window with jQuery
You can use .resize() to get every time the width/height actually changes, like this:
$(window).resize(function() {
//resize just happened, pixels changed
});
You can view a working demo here, it takes the new height/width values and updates them in the page for you to see. Remember the event doesn't really start or end, it just "happens" when a resize occurs...there's nothing to say another one won't happen.
Edit: By comments it seems you want something like a "on-end" event, the solution you found does this, with a few exceptions (you can't distinguish between a mouse-up and a pause in a cross-browser way, the same for an end vs a pause). You can create that event though, to make it a bit cleaner, like this:
$(window).resize(function() {
if(this.resizeTO) clearTimeout(this.resizeTO);
this.resizeTO = setTimeout(function() {
$(this).trigger('resizeEnd');
}, 500);
});
You could have this is a base file somewhere, whatever you want to do...then you can bind to that new resizeEnd event you're triggering, like this:
$(window).bind('resizeEnd', function() {
//do something, window hasn't changed size in 500ms
});
You can see a working demo of this approach here
​
Another way of doing this, using only JavaScript, would be this:
window.addEventListener('resize', functionName);
This fires every time the size changes, like the other answer.
functionName is the name of the function being executed when the window is resized (the brackets on the end aren't necessary).
This can be achieved with the onresize property of the GlobalEventHandlers interface in JavaScript, by assigning a function to the onresize property, like so:
window.onresize = functionRef;
The following code snippet demonstrates this, by console logging the innerWidth and innerHeight of the window whenever it's resized. (The resize event fires after the window has been resized)
function resize() {
console.log("height: ", window.innerHeight, "px");
console.log("width: ", window.innerWidth, "px");
}
window.onresize = resize;
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>
If You want to check only when scroll ended, in Vanilla JS, You can come up with a solution like this:
Super Super compact
var t
window.onresize = () => { clearTimeout(t) t = setTimeout(() => { resEnded() }, 500) }
function resEnded() { console.log('ended') }
All 3 possible combinations together (ES6)
var t
window.onresize = () => {
resizing(this, this.innerWidth, this.innerHeight) //1
if (typeof t == 'undefined') resStarted() //2
clearTimeout(t); t = setTimeout(() => { t = undefined; resEnded() }, 500) //3
}
function resizing(target, w, h) {
console.log(`Youre resizing: width ${w} height ${h}`)
}
function resStarted() {
console.log('Resize Started')
}
function resEnded() {
console.log('Resize Ended')
}

Categories

Resources