Changing functions based on screen size - javascript

I'm trying to execute functions based on the user screen size. I managed to do so with the following code:
var width = $(window).width();
if (width > 1000) {
slideshow();
tablet();
if (width > 1600) {
audio();
}
}
else {
phone();
$('.menu').localScroll();
}
When the user is changing his screen size while he is already inside the website (like resizing or changing orientation mode) the previous functions that were executed are still taking effect, which creates conflict with he latest functions that are trying to get executed.
I tried add the following code to the one listed above:
$(window).resize(function() {
$('.logo').unbind();
$('.menu-item').unbind();
$('.menuList').unbind();
$('.icon-menu').unbind();
$('.menuListItem').unbind();
$('.menu').unbind();
$('.info').unbind();
if (width > 1000) {
slideshow();
tablet();
if (width > 1600) {
audio();
}
}
else {
phone();
$('.menu').localScroll();
}
});
This code .unbind() every element that is being effected by the previous functions when the user resizing the browser, but it still loads the previous functions (phone/tablet).
I'm looking for a way to remove the unnecessary functions when the screen size is being resized.
live example can be viewed at this website

Try this:
function res(){
var width = $(window).width();
$('.logo').unbind();
$('.menu-item').unbind();
$('.menuList').unbind();
$('.icon-menu').unbind();
$('.menuListItem').unbind();
$('.menu').unbind();
$('.info').unbind();
}
$(window).ready(res).resize(res);

Related

Jquery function only loads after page refresh

I have roughly around 50 video thumbnails on a set page.
I would like to resize them depending on the resolution.
What I have tried was using #media query in css that did not work as expected then I moved over to this.
$(document).ready(function(event) {
var width = $(window).width();
// Change thumbnail size if browser width changes (should be in real-time)
if (width <= 1300) {
console.log(width);
$('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
} else {
$('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
}
});
After inserting that script the video thumbnail size changes but as I adjust the browser the jQuery does not load and resize the thumbnail unless the page is refreshed ?
Im not sure as to why the jQuery is not loading the script in real time as the size (browser) changes.
Languages that I am using in this project : PHP, jQuery
you need to catch window resize event with jQuery and also write your code there.
$(window).resize(function() {
var width = $(window).width();
// Change thumbnail size if browser width changes (should be in real-time)
if (width <= 1300) {
console.log(width);
$('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
} else {
$('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
}
});
To reduce code repetition you can make a function and call it in both $(window).resize() and $(document).ready()
function onResize() {
var width = $(window).width();
if (width <= 1300) {
$('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
} else {
$('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
}
}
$(document).ready(onResize);
$(window).resize(onResize);
This should work, but it would be much better if it were done with css. Would love you help you with that if you want to post what you tried. If you do it with css, you will not have the jumping on the page that'll occur when the js loads and changes those classes in and out.
You can do smth like this.
Note: this is untested code
function updateSizes(){
var width = $(window).width();
if (width <= 1300) {
$('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
} else {
$('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
}
}
$(document).ready(function(event) {
updateSizes();
// do other stuff here
});
$( window ).resize(function() {
updateSizes();
// do other stuff here
});

True/False depending on screen size dynamically?

I'm following a guide that allows Google Map screen to disable scrolling depending on the screen size. The only part i'm struggling is to write a code that dynamically changes the True/False value when i resize the screen manually.
This is the website that I followed the instruction but I can't seem to write the correct syntax code to produce the dynamic true false value depending on the screen size https://coderwall.com/p/pgm8xa/disable-google-maps-scrolling-on-mobile-layout
Part of the code that i need to use:
$(window).resize()
And then:
setOptions()
So I'm struggling to combine them together.
I have tried something like this:
var dragging = $(window).width(function resize() {
if (dragging > 560) {
return true;
} else {
return false;
}
});
The article you linked to is lacking important information as it fails to mention that $ is (presumably) jQuery. But you don't need jQuery at all.
What you can use instead is the MediaQueryList. It is similar to media queries in CSS, but it is a JavaScript API.
The following is an untested example of how you might use it with a MediaQueryList event listener. It sets the initial value and listens to changes to your media query with a handler that uses setOptions from the Google Maps API.
var mql = window.matchMedia('(min-width: 560px)');
var isDraggable = mql.matches;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
draggable: isDraggable
});
}
function mqChange(e) {
map.setOptions({draggable: !!e.matches});
}
mql.addListener(mqChange);
You could add an event listener to the resize event and set a value of your variable whenever the size of the window is changed:
var dragging = false;
window.addEventListener('resize', function(event) {
dragging = window.innerWidth > 560;
});
Since you mentioned that you want to disable scrolling when the windows size extends a certain value, it might be easier to just do this. If you try it you can see in the console that the value changes whenever you resize your window):
window.addEventListener('resize', function(event) {
console.log(window.innerWidth);
if (window.innerWidth > 560) {
// disable scrolling or do whatever you want to do
}
});
BTW, in your code you do this:
if (dragging > 560) {
return true;
} else {
return false;
}
You can simplify this to:
return dragging > 560
Which is exactly the same.
You can use this function to get the width and height on a resize of the screen.
$(window).resize(function() {
$windowWidth = $(window).width();
$windowHeight = $(window).height();
// run other functions or code
});
But, if you want to only show/hide a html element based on the screen size, you can also use plain html/css.
<div id="maps"></div>
Css:
#media only screen and (max-width: 560px) {
#maps {
display: none;
}
}
you can use the matchMedia function to run a callback whenever the media query status is changing
var mql = window.matchMedia('(min-width: 700px)');
function mediaHandler(e) {
if (e.matches) {
/* the viewport is more than 700 pixels wide */
} else {
/* the viewport is 700 pixels wide or less */
}
}
mql.addListener(mediaHandler);

Javascript scroll addClass

I want my navbar to be transparant on the top and bottom of my page but i want it to not be transparant in the middle. When i have my webpage on full screen this works:
$(window).on("scroll", function () {
if ($(window).scrollTop() > 720 && $(window).scrollTop() < 1450 ) {
$(".nav").addClass("active");
} else {
$(".nav").removeClass("active");
}
})
But when it gets resized this wont work anymore because the sizes change. Is there a way to do this with % instead of just normal numbers so it will be responsive?
It occur because you hardcoded your height values. Check the whole site height, divide it on three and incorporate this variables to your if statement. Every time you resize browser window it will recalculate your new position.
window.addEventListener('resize', function() {
//one third and two third of website
oneThird = window.scrollHeight / 3;
twoThird = onethird * 2;
if ( $(window).scrollTop() > oneThird && $(window).scrollTop() < twoThird ) {
$(".nav").addClass("active");
} else {
$(".nav").removeClass("active");
}
}
You can use Media Queries with JS too, so you can do certain things on your desired window size, this might help https://www.w3schools.com/howto/howto_js_media_queries.asp

How to detect a browser screen width increase past a certain point using jQuery?

basically, what I want to do is trigger an event if the user increases the size of the browser from X to Y. Provided X = Anything less than 750 pixels, and Y is anything more than 750 pixels.
Right now, I am doing something like this:
$(window).resize(function(){
if ($(window).width() >= 750) {
console.log('750 or more');
}
});
This works, however, its clearly not efficient. For example, if I resize my window from 780px to max width (1024px), even then the event gets triggered. Or even if I decrease the size from 800px to 780px, I still obviously get the console output.
How do I get this to work right?
You will need to setTimeout to allow check to take place .
Example :
var resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
var body_size = $(window).width();
// ...
// do your screen check here
// ...
}, 1);
})
Hope this helps
There's no true solution for this issue since removing the on resize event after max width has been reached results in the on resize function no longer being called even when the width is below 1024px.
Maybe in the future it's possible to have an on resize event under certain conditions only.
You can also use the on resize end event to only trigger the function after resizing the window, keep in mind this might result in visual changes happening after a user has resized a window instead of during the resizing of a window.
There are multiple methods to make the on resize event perform better: http://bencentra.com/code/2015/02/27/optimizing-window-resize.html
Here is a throttled version using script that might be a good start
Fiddle demo
(function(timeout,bigger) { // local static var - timeout,bigger
window.addEventListener("resize", function(e) {
if ( !timeout ) {
timeout = setTimeout(function() {
timeout = null;
actualResizeHandler(e);
// Set the actual fire rate
}, 66);
}
}, false);
function actualResizeHandler(e) {
// handle the resize event
if (window.innerWidth >= 750 && !bigger) {
//passed above (or equal) 750
document.querySelector('span').style.color = 'blue';
document.body.innerHTML += '<br>above 750';
} else if (window.innerWidth < 750 && bigger) {
//passed below 750
document.querySelector('span').style.color = 'red';
document.body.innerHTML += '<br>below 750';
}
bigger = (window.innerWidth >= 750);
}
// run once at load
bigger = (window.innerWidth < 750);
actualResizeHandler();
}(null,false));
<span>This text is blue on big and red on small</span>
and here is one use CSS media query
span {
color: red;
}
#media screen and (min-width: 750px) {
span {
color: blue
}
}
<span>This text is blue on big and red on small</span>

Trouble centering and dynamically resizing image using jQuery

Usually I'm able to figure things out given enough time (hence my first post here), but I've been beating my head against the wall for a while now on this one.
I'm trying to:
Center image using jQuery (it's an <img> tag, not background image on a <div>),
Load the correct image size on (window).load, and
Load a new img file at certain breakpoints as the window is re-sized.
Here is my current attempt. The centering script works perfectly. Also, the correct image file is loaded. However, I cannot get the re-size portion to work when the window is made wider or narrower (the image file does not dynamically reload).
CODE:
<!-- Center Floating Div Elements -->
<script>
jQuery.fn.center = function () {
this.css("position","absolute");
this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
return this;
}
$(window).load(function(){
$('.laptop').center();
window.onresize = function(event) {
$('.laptop').center();
}
});
</script>
<!-- Load correct image size on window load -->
<script>
$(function(){
if($(window).width() >= 0 && $(window).width() <= 900){
$("img").attr("src","/images/laptop-900.png");
}
else if($(window).width() > 900 && $(window).width() <= 1400){
$("img").attr("src","/images/laptop-1500.png");
}
else{
$("img").attr("src","/images/laptop-2100.png");
}
})
</script>
<!-- Re-load new image size on window resize -->
<script>
$(window).onresize = function(){
if($(window).width() >= 0 && $(window).width() <= 900){
$("img").attr("src","/images/laptop-900.png");
}
else if($(window).width() > 900 && $(window).width() <= 1400){
$("img").attr("src","/images/laptop-1500.png");
}
else{
$("img").attr("src","/images/laptop-2100.png");
}
});
</script>
The relevant HTML is just a tag with a class of "laptop", wrapping around an image tag (which is where I want the image source to dynamically change).
lharby: here was my attempt at your suggestion, couldn't get it to work either:
<script>
var picresize = $(function(){
if($(window).width() >= 0 && $(window).width() <= 900){
$("img").attr("src","/images/laptop-900.png");
}
else if($(window).width() > 900 && $(window).width() <= 1400){
$("img").attr("src","/images/laptop-1500.png");
}
else{
$("img").attr("src","/images/laptop-2100.png");
}
});
$(window).load(function(){
$picresize();
window.onresize = function(event) {
$picresize();
}
});
</script>
So to elaborate on the comments. I made this fiddle:
https://jsfiddle.net/lharby/5p2xdnaf/
There is now a single function called chImage which checks window width and can then be triggered on various events.
I've also stored window width in a variable to make the code a bit cleaner and easier to read (you could also set your sizes in variables, and then change them later if needed, so only write them once).
var chImage = function(){
var winWidth = $(window).width();
if(winWidth >= 0 && winWidth <= 900){
$("img").attr("src","http://placehold.it/350x150");
}
else if(winWidth > 900 && winWidth <= 1400){
$("img").attr("src","http://placehold.it/500x300");
}
else{
$("img").attr("src","http://placehold.it/800x400");
}
};
Then call this function and bind it to whatever events we want.
$(window).on("load resize", function(){
chImage();
});
EDIT
I did move the centering function below to make sure it wasn't intefering with this function, but the centering can be achieved with css. I will try and update.
Chris Coyier has made an utterly interesting article about figuring out responsive images.
The image centering can be done in CSS, no need for scripts. See centering things and solved by flexbox.

Categories