This is the JS code i'm using:
$("document").ready(function($){
var nav = $('#menu2');
$(window).scroll(function () {
if ($(this).scrollTop() > 90) {
nav.addClass("f-nav");
} else {
nav.removeClass("f-nav");
}
});
But i can't seem to get this into my code.
function checkWidth(init){
/*If browser resized, check width again */
if ($(window).width() < 514) {
$('html').addClass('mobile');
}
else {
if (!init) {
$('html').removeClass('mobile');
}}}$(document).ready(function() {
checkWidth(true);
$(window).resize(function() {
checkWidth(false);
});
And what i want is that when .f-nav is added to #menu2, when the screen is <1050 the classshould be removed.
To change html to #menu2, just replace one with the other. jQuery is pretty simple in this respect
if ($(window).width() < 514) {
$('#menu2').addClass('f-nav');
} else {
$('#menu2').removeClass('f-nav');
}
JSFiddle
There are a few ways to do that:
Javascript only
See it in action: Fiddle
$(window).resize(function() {
if ($(window).width() < 1050) {
$selector.removeClass('my-class');
} else {
$selector.addClass('my-class');
}
}).resize(); // trigger resize event initially
And don't forget: You don't have to place $(window).resize inside $(document).ready.
Mixed Javascript & CSS
See it in action: Fiddle
This technique is explained here: http://www.senaeh.de/media-query-variablen-javascript-auslesen/
Basic principle: set a variable with a CSS pseudo element and get it with javascript.
This workaround is good if you have to use Javascript even if media queries are used, because you don't have to declare the breakpoint twice.
CSS
#media screen and (max-width: 1050px) {
body:after {
content: 'tablet';
display: none;
}
}
Javascript
var mode = window.getComputedStyle(document.body,':after').getPropertyValue('content');
Be aware: IE < 9 doesn't support getComputedStyle. You have to use a polyfill like this one.
this is best achieved with a media query
#media screen and (max-width:1050px){
.mobile{
/* will only apply on devices narrower than 1050px */
}
}
EDIT: also possible to use media queries with javascript in modern browsers
if (matchMedia) { // check if browser supports media queries from JavaScript
var mq = window.matchMedia("(max-width: 1050px)");
WidthChange(mq);
// every time width changes, check the media query
mq.addListener(function WidthChange(mq){
if(mq.matches){
//we are in a mobile size browser
$('#menu2').addClass('mobile');
$('#menu2').removeClass('f-nav');
} else{
// desktop browser
$('#menu2').addClass('f-nav');
$('#menu2').removeClass('mobile');
}
});
}
When you load a website on a screen bigger than your breakpoint, the script wont work, because you need to re-calculate the screen size(refresh the page in this case). You need to get the width of the screen on resize. Use resize() method, and inside it place your test condition, and assign the class to your element. Reference to help you: http://api.jquery.com/resize/
If you want to change the class of a div in JS, you can do something like that:
document.getElementById("#YourId").className = "YourNewClass"
It will just change your class attribute :-)
Like that, you can also check which class is used and do what you want to do with that.
Edit thanks to Olaf Dietsche: this must be a duplicated post, here can be your answer: jquery, add/remove class when window width changes
Related
I have a navigation menu set to display:none, which appears upon scroll and disappears once back at the top.
Is there a way to disable the scroll function once I reach a certain breakpoint (ex. max-width: 786px) and display the menu?
Javascript
$(window).on("scroll", function() {
if($(window).scrollTop()) {
$('nav').addClass('show');
}
else {
$('nav').removeClass('show');
}
})
CSS
.show {
display: block
}
You can solve this using either javascript or CSS, however I would personally go with the javascript one.
First up, for a javascript solution, the function you need is:
window.innerWidth
It will return the entire window width not including scroll bars. Read more about it here.
So, as Temani Afif suggested, you would write a test inside your scroll function to check for the desired window width like so:
$(window).on("scroll", function() {
if (window.innerWidth <= 786) return;
// Your other code here
})
For a purely CSS solution, you could override the effect of the 'show' class with a media query:
.show {
display: block
}
#media screen and (max-width: 786px) {
nav {
display: block !important
}
}
More on media queries here
You can activate/deactivate the scroll listener on browser resize. This way your scroll listener wont be called everytime user scrolls when browser width is more than 786px.
var scrollListenerActive = false;
var handleScrollListener = function() {
if( $(window).width() < 786 && !scrollListenerActive ) {
$(window).on("scroll", function() {
if($(window).scrollTop()) {
$('nav').addClass('show');
}
else {
$('nav').removeClass('show');
}
});
scrollListenerActive = true;
} else {
$(window).off("scroll");
scrollListenerActive = false;
}
}
$(document).ready(handleScrollListener); // attach the listener on page load
$(window).resize(handleScrollListener); // attach/remove listener on window resize
That's a good strategy above, however the event you want to listen for is simply 'resize', on the window object (some older browsers can do it on any dom element, but better to be consistent and current with the standard).
So something like:
window.addEventListener('resize',function(){
if(window.innerWidth >= 768){
document.body.style['overflow-x'] = 'hidden';
}
else{
document.body.style['overflow-x'] = 'auto';
}
});
You can trade 'auto' for 'scroll' if you want the scrollbar to always show when less than 768.
Similarly, you can switch out 'overflow' instead of 'overflow-x' if you want to affect both scrollbars.
Keep in mind that the event tends to fire for every width and height change as the window is resized, in case you have other logic that might have an issue with firing many times (thousands or more) as it is resized.
This also works on maximize/restore, as they trigger the resize event as well.
Here's MDN's doc on the resize event if needed:
https://developer.mozilla.org/en-US/docs/Web/Events/resize
This is vanilla javascript, so it should work whether you're using a lib like jquery or not.
I want to make my site mobile friendly but I run into one problem.
I have an player of a streaming plattform on my main page, which is invisible/hidden on a certain width by using media queries in CSS, but it still gets loaded.
I want to remove this container/iframe completly for any width lower than 1280px or 768px.
I've tried to fiddle around with jquery/javascript a bit but it's not working for me and I need some help :D
This is what I tried to use:
$(window).resize(function() {
if ($(window).width() < 1280) {
$(container_selector).document.getElementById("video-container"){
this.pause();
delete(this);
$(this).remove();
});
$(container_selector).empty();
}
});
This is the container/iframe I want to remove:
<div id="video-container"><iframe src="http://www.hitbox.tv/embed/kazuto" width="300" height="150" frameborder="0" allowfullscreen="allowfullscreen"></iframe></div>
Thanks in advance :)
You can use media queries.
For instance, like this:
#media (max-width: 1280px) {
#video-container {
display: none;
}
}
Here is the code to remove the whole div and the iframe inside.
$(window).resize(function () {
if ($(this).width() < 1280) {
$("#video-container").remove();
}
});
But since you trigger it on resize, what's when the window width increases again? If you just want to hide the iframe on lower resolutions and show it again when user resizes back to higher resolution, then I would recommend to use hide() and show() (or use the answer proposed by #Sergey Kopyrin)
Code sample
$(window).resize(function () {
if ($(this).width() < 1280) {
$("#video-container").hide();
} else{
$("#video-container").show();
}
});
You can also specify a duration parameter inside those methods (e.g. $("#video-container").hide(500) ) so it will not be hidden abruptly.
For example here is a fiddle which shows how to change a font when the width drops below 200px.
#media (max-width: 200px) {
.test {
font-size:40px;
}
}
If you move the html window to the right to make it smaller you will see the point at which it hits 200px b.c. the font will change.
If someone could add a dynamic div to the fiddle so that this value would be output to the window this would be a cool test script for media queries.
Also, if there is a good reference on the web for the JavaScript interface to media queries. I hope there is one. I have not found it yet.
You can add an event listener to window.matchMedia
if (matchMedia) {
var mq = window.matchMedia("(max-width: 200px)");
mq.addListener(WidthChange);
WidthChange(mq);
}
// media query change
function WidthChange(mq) {
if (mq.matches) {
console.log('matches')
}
}
Demo
I did using jQuery, hope this helps.
$( window ).resize(function() {
if($(window).width()<=200){
$(".test").css("font-size","40px");
}
else{
$(".test").css("font-size","20px");
} });
http://jsfiddle.net/7gup43rx/2/
Here is what you were actually asking for. The snippet below will output the dimensions that media query uses.
http://jsfiddle.net/jbnt7nh1/8/
// some code - updated fiddle
Here is a good point to start reading about the different widths in CSS.
https://www.google.com/#q=quirksmode+screen+width
When the screen is on a certain width, we wish to hide a button and, instead, allow the wrapper div to be clickable.
That should only happen, however, when:
#media only screen and (min-width:320px) {
While we can easily display:none; and display:block; the button, the issue arrives when we want to remove the surrounding wrapper div (on higher screen sizes), because, if we display: none; the surrounding div, all their inside content will be removed too!
Is there any javascript version of the media query above, that could be reliable cross browser, and cross OS, that one may have, in order to dynamically add and remove the element on certain screen conditions?
Yeah check this:
https://developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia
Syntax
mql = window.matchMedia(mediaQueryString)
Where mediaQueryString is a string representing the media query for which to return a new MediaQueryList object.
Example
if (window.matchMedia("(min-width: 400px)").matches) {
/* the view port is at least 400 pixels wide */
} else {
/* the view port is less than 400 pixels wide */
}
And a polyfill like this:
https://github.com/paulirish/matchMedia.js/
Old IE:
https://github.com/benschwarz/matchMedia.js/tree/IE7-8
If you just care about a simple check here's how you could do it with jQuery, though it is pretty trivial to do it in plain Javascript too this is just easier because of your old IE requirements:
var timeout;
function onWindowResize() {
var width = $(window).width();
if (width <= 480) {
console.log('small');
} else if (width <= 767) {
console.log('medium');
} else if (width <= 1024) {
console.log('large');
} else {
console.log('xlarge');
}
}
$(window).resize(function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
onWindowResize();
}, 50); // Only resize every 50ms - number up to you.
});
Don't use JS to change the display property on the element directly. Modify the class names that are associated with the element instead.
You can then define display: none or otherwise using a class selector and media queries in your external stylesheet.
So basically, I want a div called #content to have a css top value of 200px if the browser height is less than 440px. However, this seems to not be working. What am I doing wrong?
var boh = $(window).height();
var bohi = parseInt(boh);
if(bohi < 440) {
$("#content").css("top","200px");
} else {
//this part works, so it's hidden
}
I think you need to handle $(window).resize() event or that logic is only going to be run once.
<script type="text/javascript">
$(window).resize(function(){
var bohi = $(window).height();
if(bohi < 440) {
$("#content").css("top","200px");
} else {
//this part works, so it's hidden
}
});
</script>
Here is a jsfiddle that seems to be working:
http://jsfiddle.net/kNbuy/
Note that $(window).height() doesn't need the parseInt() its already treated as a number.
You need to place this code in your document ready handler like so:
<script>
$(document).ready(function(){
var boh = $(window).height();
var bohi = parseInt(boh);
if(bohi < 440) {
$("#content").css("top","200px");
} else {
//this part works, so it's hidden
}
});
</script>
OK. I think I see what your problem could be.
You haven't specified what the 'position' attribute of your #content element is. If you're not getting the behavior you want, I suggest that you try adding position:absolute to the style for #content.
I recommend that you carefully study how the 'position' attribute works. You may be surprised by the results you get by changing the position css attribute of #content and it's parent element.
Also, you may want to consider having the page automatically execute some code to adjust itself whenever the user resizes the browser window. This can be handled with $.resize().
As of 2015, I recommend using CSS media queries for this instead of JavaScript.
#media (max-height: 440px) {
#content {
top: 200px;
}
}