How can i do this if statement without refreshing the page? - javascript

I'm building a responsive website using css medias and JQuery.
I created a script to check the page width:
if ($(window).width() < 1240) {
$("#menu").toggle(); //hide menu
$('#body-wrap').toggleClass('shifted'); //puts the body width to 100%
$('#navbar').toggleClass('shifted'); //puts the navbar width to 100%
}
But this code only works when I refresh the page.
How can I do it automatically?
Thanks.

Put it in a resize event.
window.addEventListener('resize', function () {
// Your code
});
You may want to consider using CSS to do this instead, though (look at media queries for that)

You have to add it to the onresize event:
https://developer.mozilla.org/en-US/docs/Web/API/Window.onresize
This event will be called each time when you resize the window, so you can respond to those changes.
But I think a better option would be to use CSS media queries, like so:
#media only screen
and (max-device-width : 1240px) {
#menu {
display: none;
}
}
Example and info on: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/

Related

How to live update CSS based on screen size, using JQuery?

I pulled a snippet of JS from a response to:
How can I make content appear beneath a fixed DIV element?
The JS works great but only when the page first loads, if the screen size changes for whatever reason, the rendered page is then in error until refreshed.
I currently have this:
$(document).ready(function() {
var contentPlacement = $('#topMenu').position().top + $('#topMenu').height();
$('body').css('margin-top',contentPlacement);
$('#navWindow, #searchWindow').css('margin-top',-contentPlacement);
});
Is there a way to have the outputted CSS dynamically change at the moment the screen size updates? This will also be helpful while developing the site.
This will be for displaying the content on my page underneath a fixed menu.
UPDATE
The sample of the site is located here: http://wp19.knowgreaterpartnership.com/
Additionally to the ready Callback function you can also use jquery.resize. You just have to execute the same code on the resize callback. Resize will be called every time the window size changes.
For the sake of less code redundancy I introduced a new method adjustContent:
$(document).ready(adjustContent);
$(window).resize(adjustContent);
function adjustContent() {
var contentPlacement = $('#topMenu').position().top + $('#topMenu').height();
$('body').css('margin-top',contentPlacement);
$('#navWindow, #searchWindow').css('margin-top',-contentPlacement);
}
I know you're asking about using jQuery to change CSS, but what you really should be doing is using Media Queries for your css so that it's declarative instead of script/event initiated.
Ex: (https://www.w3schools.com/Css/css3_mediaqueries_ex.asp )
/* Set the background color of body to tan */
body {
background-color: tan;
}
/* On screens that are 992px or less, set the background color to blue */
#media screen and (max-width: 992px) {
body {
background-color: blue;
}
}
/* On screens that are 600px or less, set the background color to olive */
#media screen and (max-width: 600px) {
body {
background-color: olive;
}
}

Animation in jQuery works on desktop but not in mobile

I have an animation that triggers when the page load and it is an image going from right to left, very straightforward. Now, it works very well on desktop but not so good in mobile. Is there any way to apply something like a media queries as it is done with css but for jQuery?
You can actually try to combine CSS media queries and JS, by using a hidden element and setting a specific value for some CSS property like z-index. You can then check the value of this property with JS and set a mobile variable accordingly.
I've found that this works more accurate than trying to get the viewport width in JS. Or at least it makes sure that the point at which the variable is true in JS is exactly the same as when the changes to the CSS occur.
CSS
#test {
display: none;
z-index: 1;
}
#media only screen and (max-width: 400px) {
#test {
z-index: 2;
}
}
JS
(function($) {
var $test,
isMobile = false;
function checkTest() {
if ($test.length) {
isMobile = $test.css('z-index')=='2';
}
}
$(function() {
$test = $('#test');
checkTest();
});
$(window).on('resize',function() {
checkTest();
});
// in the rest of your code you can now simply check if isMobile is true
})(jQuery);
Edit
Preferably you should not be using an extra hidden element just for this purpose. You should usually have some existing element that is altered in some way by the media query and you can check for that. Like a header that is fixed in desktop view but not for mobile, or perhaps a logo that is 200px wide for desktop and only 100px for mobile. You get the idea.

How to hide a external script when browser window resizes

So I have an external script(a chatterbox one) hosted on another website. It's positioned to the right of my list with float:right. The problem I have is that when the browser window resizes, it overflows onto the list. I have tried overflow:hidden; but that doesn't work.This is what happens when the browser window overflows.
This is how it normally looks.
Try using a CSS media query, like this:
#media (max-width:600px) {
#chat-box {
display: none;
}
}
This can be read as:
If the screen is less than 600px wide, hide the element with the id chat-box.
Place this in a style tag or in a .css file.
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
Try using a CSS important, like this:
overflow: hidden !important;

How to use .load to .prepend content without page refresh?

I'm trying to use jQuery to only load certain content if the viewport is above a specified width.
This works, but not quite right. Check out the JsFiddle link at the bottom for a working demo.
Here's what I have so far;
If the viewport is below 500px #wrapper is hidden with a media query.
Above 500px #wrapper is set to visibility: visible;
jQuery is looking for element.is(':visible'). When this happens jQuery loads the image.
Resizing the browser window activates the media query, but not the jQuery.
The jQuery only fires on a page refresh.
I've tried using $( window ).resize(function() but this fires every time the viewport changes size, duplicating the content.
Is there a way to activate jQuery without a page refresh?
The ideal solution would be;
up to 500px load nothing,
when the viewport is resized above 500px load the jQuery.
If the viewport is resized below 500px unload the jQuery content.
HTML
<p>CSS hides <strong>#wrapper</strong> if viewport is below 500 pixels.</p>
<div id="wrapper">
<p>jQuery checks CSS to see if <strong>#wrapper</strong> is visible and loads image on page refresh.</p>
<p>I'm looking for a way to run this function without needing to refresh the page. I've looked into using (resize) function, but this duplicate the content.</p>
CSS
#wrapper {
visibility: none;
display: none;
}
#media only screen and (min-width: 500px){
#wrapper {
visibility: visible;
display: block;
}}
JQuery
$(function() {
var element = $(this).find('#wrapper');
if (element.is(':visible')) {
$('#wrapper').prepend('<img src="http://cache.desktopnexus.com/thumbseg/1134/1134934-bigthumbnail.jpg" alt="Demo image">');
}
JsFiddle link:
https://jsfiddle.net/tu60wbbu/13/
You can use window.matchMedia() instead of $(window).resize() to have your javascript respond to a media query match in your CSS.
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
It's fairly well supported across browsers.
http://caniuse.com/#search=matchmedia
If you need to support IE 9 or lower, you might have to fall back to using $(window).resize() for those browsers.
Here is the code for my comment:
$(function() {
var large = false;
var barrier = 1000;
$( window ).resize(function() {
if(!large && $(window).width() > barrier) {
large = true;
$('#wrapper').prepend('<img src="http://cache.desktopnexus.com/thumbseg/1134/1134934-bigthumbnail.jpg" alt="Demo image">');
} else if(large && $(window).width() < barrier) {
large = false;
$('#wrapper img').remove();
}
});
});
Working Fiddle: https://jsfiddle.net/tu60wbbu/14/
I used 1000px as the barrier in the demo.
You should initialize large properly by the window width on load. For demo purposes i used false as initial value.
Sorry for the long time, I was at vaccation :-)

How to remove clone() rule in Javascript when screen width is smaller than

I've been fiddling around with my navigation menu and decided to add a feature when you scroll down past a certain point the NAV slides down into viewport so that the user doesn't have to scroll back up to the top of the page to navigate. This is something that's become quite popular lately.
So I fiddled around and this javascript did the trick (note that I am not fluent with jquery at all):
jQuery(document).ready(function($){
$(".menu_wrapper").before($(".menu_wrapper").clone().addClass("shrink"));
$(window).on("scroll", function () {
$("body").toggleClass("slidedown", ($(window).scrollTop() > 700));
});
});
Now I read that as ... duplicate or 'clone' (make another) .menu_wrapper element before the original + add the class .shrink to it ... AND only once we've scrolled past 700px, we'll see this duplicate NAV because of the class .slidedown
CSS:
.shrink { position:fixed; top:-400px; left:0; width:100%; border-top: 0px solid #35d3c3; z-index:99999}
.slidedown .shrink { top:0;}
Now this is working 100% and I'm stoked BUT (it's never smooth sailing is it!!!) now I've got a problem when I change my viewport to a screen width less than 767px - YES my website is responsive and this is where my NAV changes to the typical drop down (even without the javascript / effect above) by using css and javascript:
jQuery(document).ready(function($){
$('.menu_wrapper').prepend('<div id="menu-icon">Menu</div>');
$("#menu-icon").on("click", function(){
$("#menu").slideToggle();
$(this).toggleClass("active");
});
});
My problem is that there is now a duplicate dropdown prepended NAV (1 on top of the other), like so:
+ MENU
+ MENU
The one NAV works but the other doesn't ... anyway regardless, when my media query hits 'mobile status' (below 767px) and the NAV prepends to a dropdown, this is when I DON'T want the whole slide-down-effect-clone (first jquery posted above) thing anymore. I want that rule to almost not exist or not apply when I'm below 767px screen width. How can I do this?
I've tried one of the obvious like:
.shrink { display:none}
.slidedown .shrink { display:none}
which almost seems like I've hit the jackpot leaving me only 1 prepended menu:
+ MENU
but nothing happens when I click on it - it doesn't slidedown and show the menu list items.
but I'm thinking like adding a rule within for the javasacript:
jQuery(document).ready(function($){
$(".menu_wrapper").before($(".menu_wrapper").clone().addClass("shrink"));
$(window).on("scroll", function () {
$("body").toggleClass("slidedown", ($(window).scrollTop() > 700));
});
});
that when we get below a width of 767px, we ignore the clone() function / rule etc?
I've done some googling of removeclass etc but because I'm a bonehead at javascript, I'm probably doing it all wrong.
Any help I'd appreciate it?
Since you want to hide that menu based on certain viewport dimensions, why not use a media query?
#media all and (max-width: 766px){
.shrink{ display: none; }
}
or
.shrink{ display: none; }
#media all and (min-width: 767px){
.shrink{ display: block; }
}
(That might not be the best width values or CSS properties to use there, but that should get you started.)
Edit: If you wanted to do the entire thing in javascript, the matchMedia() API is there for you, too.
If the CSS media query approach that ajm posted does not work for you, you could try only executing your code if a media query is met. The code in handleMediaQuery() will only run if the width is above 767px;
//Media query listeners
var mql = window.matchMedia("(min-width: 767px)");
mql.addListener(handleMediaQuery);
handleMediaQuery(mql);
function handleMediaQuery(mql) {
if (mql.matches) {
// Do stuff here that you want done when the query matches
}
else {
// Do stuff here that you want done when the query does not match
}
}
See https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries for more info

Categories

Resources