How do I disable a particular script depending on media query? - javascript

Been struggling with this one, can't get it to work. I only want this script to work for desktop.
Thanks.
<script type="text/javascript">
$(document).ready(function() {
$('#scroll_top').hide();
});
$(window).scroll(function() {
if ($(this).scrollTop() == 0) {}
if ($(this).scrollTop() >= 1000) { // If page is scrolled more than 50px
$('#scroll_top').fadeIn(300); // Fade in the arrow
} else {
$('#scroll_top').fadeOut(300); // Else fade out the arrow
}
});
$('#scroll_top').click(function() { // When arrow is clicked
$('body,html').animate({
scrollTop: 0 // Scroll to top of body
}, 500);
});
</script>

I would test for window size, not device type. Testing for window size is more accurate than testing for device and besides, if someone does have a big screen with 15 thousand (yes, I'm exaggerating on purpose:) ) windows open and resized very small, would you want this script to run? Probably not.
BUT . . .
I recognize this script as a "scroll to top" buttons script, perhaps you DO want it to work on smaller devices, just with a smaller image? I personally find them very useful as long as they are sized small enough to not block content . . just my 2 cents,. I'm sure you know your website better than me.
Good luck!

What do you mean by desktop? like computers ?
If yes add the if condition below :
if( !(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) ) {
// Your code
}
The condition bellow spot all the smartphone or tablet browser.
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
The "!" before the condition make it spot all the others : so computers ones.
You can also try with window width if the window width is lower than 1024px you can assume that the device would be a tablet or a smartphone.
if (window.innerWidth <= 1024){
//your code
}
Feel free to ask if needed.

If you want to depend on css media query you can add 3 invisible elements to your HTLM and then test if the display is set to block.
Add thes elements to your footer
#isMobile,#isTablet{
Display:none;
}
#media (max-width: 500px){
#isMobile{
Display: block;
}
}
#media (min-width: 501px) and (max-width: 1024px){
#isTablet{
Display: block;
}
}
Js
If( $("#isTablet").css("display") == "block") {
// do code
}
I don't guarantee my code works but you should get the basic idea how to use css media query in js. This way if you change breakpoint sizes you won't need to update javascript.
On other hand you can always do a simple window width test with
if( $(window).width() > 1024 ){
//do code
}

Related

Javascript code hiding a div doesn't work (CSS #media rule doesn't work either)- 'cannot read property style of null'

So, I've got a button that display toggles a div on a click event. It works properly. However, I can't hide the same div using nearly the same code (however, I want to toggle this div after my screen becomes too big, not after clicking), because I get the problem like in the title- 'cannot read property style of null'
The part that doesn't work (hiding a div after screen becomes too big:
if (screen.width > 900) {
document.getElementById('klik').style.display = 'none';
}
And the part that works (button toggles a div using a click event):
function showDiv() {
if (document.getElementById('klik').style.display == 'block'){
document.getElementById('klik').style.display = 'none';
}
else{
document.getElementById('klik').style.display = 'block';
}
}
I wrote this code because I want to do a scalable menu, displaying a div with list items inside after clicking on it. The menu button is visible only when screen-width <= 900px, if screen-width > 900px I've got a normal navigation bar and the button disappears.
Am I forgetting something? I'm new to Javascript. Also one more thing- it also doesn't work using #media rule, however I can change the background-color with #media. I hope it might help. Also thanks in advance.
Note Two Problems:
Ensure that the element you want to change it's display has the id="klik"
The below code will execute only once.
if (screen.width > 900) { document.getElementById('klik').style.display = 'none'; }
But why?
The answer is because you didn't set an event to run it every time when your resize the screen. Also, screen.width will always return the width of the display. What you are looking for is the window.innerWidth
So a possible solution:
window.addEventListener('resize', function(){
document.getElementById("screen").innerHTML = window.innerWidth.toString() + "px";
if(window.innerWidth < 900)
{
//Perform your desired Executions Here
}
});
<div id="screen"></div>
This will run the code every time a window.onresize is triggered. And that's exactly what #media in CSS does. It works on window.onresize behind the scene in javascript sense.
Note: I have added a simple illustration on how to work with screen.resize which you can use as the basis for modifying element properties based on a certain range. All you need to do, is to ensure that you do your styling within that block and it will work.
Hmmm, actually this is exactly what media queries are made for. Did you try
#media (min-width: 900px) {
#klik {
display: none;
}
}
If that doesn't work: Are there any other css styles that may overwrite that particular style? Something like #klik { display: block !important; } ...?

Remove div/iframe on certain width

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.

How do I disable the scroll to $align of this script on mobile?

I don't understand jQuery enough to either search for the solution, or try to implement one on my own. On desktop, I use a slideToggle to show/hide content based on which button is clicked. If the content window is 'shown' I scroll the screen to the top of the '#section' holding the content. I want to disable this on Mobile, becasue the content stacks into a single column on mobile and if the user clicks on the bottom of the stack, it scrolls him back to the top of the section.
This is the script:
var $align = $("#features");
function slideonlyone(thechosenone) {
$('.feature-box').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).slideToggle(400);
$("body").animate({
scrollTop: $align.offset().top
},{
duration: 1200,
queue: false
})
}
else {
$(this).slideUp(400);
}
});
}
The site can be viewed here:
www.newmarketsolar.ca
If you enable the inspector and turn on mobile emulation you can see what I mean by clicking on 'learn more' button on the last icon 'interactive' - it will scroll you up - I need to turn this off for devices only up to 768px.
Any help would be marvelous.
So what you want to do is check if the screen width is smaller than 768px first, you can do this with:
slideonlyone(thechosenone){
if($( window ).width() > 767){
// your function body
}
}
This checks if your window is bigger than 767px and otherwise doesn't execute.
edit: I didn't look at the site provided, but essentially this is what you need and can place as a condition around anything that should only happen on screens bigger than 767px
The below page has excellent article on Media query listeners in javascript,
http://www.javascriptkit.com/dhtmltutors/cssmediaqueries4.shtml
The below code should take care of your requirement,
var mql = window.matchMedia("screen and (min-width: 768px)");
if (mql.matches){ // if media query matches
var $align = $("#features");
function slideonlyone(thechosenone) {
$('.feature-box').each(function(index) {
if ($(this).attr("id") == thechosenone) {
$(this).slideToggle(400);
$("body").animate({
scrollTop: $align.offset().top
},{
duration: 1200,
queue: false
})
}
else {
$(this).slideUp(400);
}
});
}
}
The above code runs only once and should work fine on devices or when the page is loaded keeping the browser width less than 768px.

iOS 8 glitch effecting window resize

I've got some very simple code:
$(function() {
$(window).resize(function () {
if ($(window).width() < 500) {
$("#foo").show(); $("#foo2").hide();
} else if ($(window).width() > 501) {
$("#foo2").show(); $("#foo").hide();
}
}).resize();
});
All was working fine on desktop (all major browsers) and mobile (as many as I could test), till iOS 8 came out. Now when a users scrolls in Safari the javascript falls back to 'else if', creating 'foo2' and hiding 'foo' despite the browser not resizing. This is for a menu, as such the menu closes if the user scrolls which shouldn't be happening.
If I remove the window resize function all works as it should, however the menu doesn't update in real time if the user resizes the browser window.
Is there an alternative to window resize I can use to achieve the same effect?
...so, considering I get the problem as you describe it, you can avoid javascript and do it using pure css and media queries:
#media (max-width:500px) {
#foo {
display:block;
}
#foo2 {
display:none;
}
}
#media (min-width:501px) {
#foo2 {
display:block;
}
#foo {
display:none;
}
}
edit: ..this will definately have nothing to do with scrolling and will certainly be faster and cleaner
This might be a little late, but I'd store the width of the window on load and then check against that on the resize to ensure an actual resize took place horizontally. That would ensure that the code only fired when the browser changed size on the x axis.
var windowWidth = $(window).width();
$(window).resize(function(){
if (windowWidth !== $(window).width())
{
windowWidth = $(window).width();
// rest of your code goes here
}
});
Remember that the resize event could fire quite a lot while someone is resizing, so you may want to limit the whole thing using setInterval, but that's a separate discussion.

Jquery, Remove class when width screen is 1050px

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

Categories

Resources