How can I reload css styles when change windows width?
I tried this but without success. A simple reload (F5) helps to correct the css tags.
jQuery(function($){
var windowWidth = $(window).width();
var trigger = 1024;
if (windowWidth < trigger) var smaller = true;
else var bigger = true;
$(window).resize(function() {
if(windowWidth != $(window).width() &&
( ( smaller == true && $(window).width() > trigger ) ||
( bigger == true && $(window).width() < trigger )
)
){
window.location.reload();
return;
}
});
});
CSS example
.example {
display: block;
padding: 12px;
position: fixed;
top: 0;
width: 100%;
z-index: 10;
}
#media screen and (min-width: 1024px) {
.example {
left: 80px;
top: 80px;
width: auto;
padding: 8px;
}
}
The original CSS styles had been modified by some JS, so I want to reload the original when the windows becomes smaller or bigger then 1024px.
You should hook your code (whatever you want to do, i didnt understand what you want to do very well actually) inside a jquery resize event
Here is an example:
$( window ).resize(function() {
$( "body" ).prepend( "<div>" + $( window ).width() + "</div>" );
});
Dont really see the why of using javascript or jquery to change css whenever viewport vidth gets risezed, generally its just better to use css media queries.
Actually it works when you call the function with a timeout
setTimeout(function(){
window.location.reload();
},1);
Related
I want to make a div slide (in,out,left,up,right or down) when I reach a specific scrollTop() value. However, I don't want it to trigger some animation... I want the div to move with the scroll, like the effect achieved here: http://www.tioluchin.com/
so far, the "closest" I got was this:
var vistaEstandar = document.getElementById('vista');
vistaEstandar.onscroll = function() {animacionesEstandarVista()};
function animacionesEstandarVista()
{
var ypos = vistaEstandar.scrollTop;
if (($(window).width() >= 1800 && vistaEstandar.scrollTop > 6053) || ($(window).width() > 1800 && document.documentElement.scrollTop > 6053)) {
var image= document.getElementById("seccion9textoSegundo");
var toppin = ypos/6053;
image.style.top = toppin*150 + 'px';
}
else
{};
However, this doesn't work because the value I manage to set is too low.
The web I am trying to put together is long so when I multiply the value it is either too high or too low.
In the website http://www.tioluchin.com/ I want the effect the knives and food have
I went into that source code because it made me curious. I have found how they do it.
First part is catching what happens on scroll
$(document).scroll(function(){
windowScroll()
});
They have there a condition which disables it on smaller screens but that is not important here.
Second part is this:
function windowScroll(){
var st = $(document).scrollTop();
$("#aff").css({"top": 32 - st * 0.15 + "px"});
$("#aff").css({"left": 48 - st * 0.15 + "px"});
}
They have it bigger, for more elements. And this is my playground. In principle you have start with current position as an offset. "st" indicates how deep you are. st*0.15 tells you how fast the element will run from the screen.
My HTML:
<div class="wrapper">
<div id="aff" class="moving-div">
</div>
And CSS:
.moving-div {
width: 3rem;
height: 3rem;
position: relative;
top: 2rem;
left: 3rem;
background: red;
}
.wrapper {
height: 1000px;
}
I have 2 sidebar (side-bar and side-bar-mobile). First sidebar i want to see it when screen in width > 768px, so i do that.
#media only screen and (min-width: 768px){
.side-bar{
display: block;
}
.side-bar-mobile{
display: none;
}
}
And when screen in width < 768px, side-bar is hide and side-bar-mobile is show toggle when i click a button.
CSS
#media only screen and (max-width: 768px){
.side-bar{
display: none;
}
.side-bar-mobile{
display: none;
}
}
JS
$('#toggle-menu').on('click', function(e){
$('.side-bar-mobile').slideToggle();
e.preventDefault();
})
Side-bar-mobile is slide good. But when i resize my window to normal size (width > 768px), the side-bar-mobile is still show. What can i do now? I think problem in slidetoggle functions, it make side-bar-mobile is show when i resize window. But i can't solve this problem. Help me! Thank you.
When screen width > 768 the side-bar-mobile must be hidden no matter what.
So in order to do that you need to register window resize listener like this:
window.onresize = function(){
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.getElementsByTagName('body')[0].clientHeight;
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.getElementsByTagName('body')[0].clientWidth;
if(w > 768 ){
$('.side-bar-mobile').css({display:"none"});
}
}
also put window resize condition.
try this one
$(function(){
var nb = $('#toggle-menu');
var n = $('.side-bar');
$(window).on('resize', function(){
if(nb.is(':hidden') && n.is(':hidden') && $(window).width() >768) {
$('.side-bar').show().addClass('keep-nav-closed');
}
});
I want to change the order of elements in the DOM based on different browser sizes.
I've looked into using intention.js but feel that it might be overkill for what I need (it depends on underscore.js).
So, i'm considering using jQuery's .resize(), but want to know if you think something like the following would be acceptable, and in line with best practices...
var layout = 'desktop';
$( window ).resize(function() {
var ww = $( window ).width();
if(ww<=767 && layout !== 'mobile'){
layout = 'mobile';
// Do something here
}else if((ww>767 && ww<=1023) && layout !== 'tablet'){
layout = 'tablet';
// Do something here
}else if(ww>1023 && layout !== 'desktop'){
layout = 'desktop';
// Do something here
}
}).trigger('resize');
I'm storing the current layout in the layout variable so as to only trigger the functions when the window enters the next breakpoint.
Media queries are generally preferred. However, if I am in a situation where I am in a single page application that has a lot of manipulation during runtime, I will use onresize() instead. Javascript gives you a bit more freedom to work with dynamically setting breakpoints (especially if you are moving elements around inside the DOM tree with stuff like append()). The setup you have is pretty close to the one I use:
function setWidthBreakpoints(windowWidth) {
if (windowWidth >= 1200) {
newWinWidth = 'lg';
} else if (windowWidth >= 992) {
newWinWidth = 'md';
} else if (windowWidth >= 768) {
newWinWidth = 'sm';
} else {
newWinWidth = 'xs';
}
}
window.onresize = function () {
setWidthBreakpoints($(this).width());
if (newWinWidth !== winWidth) {
onSizeChange();
winWidth = newWinWidth;
}
};
function onSizeChange() {
// do some size changing events here.
}
The one thing that you have not included that is considered best practice is a debouncing function, such as the one below provided by Paul Irish, which prevents repeated firing of the resize event in a browser window:
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize');
// usage:
$(window).smartresize(function(){
// code that takes it easy...
});
So incorporate a debouncer into your resize function and you should be golden.
In the practice is better to use Media Queries
Try this, I'm in a hurry atm and will refactor later.
SCSS:
body, html, .wrapper { width: 100%; height: 100% }
.sidebar { width: 20%; height: 500px; float: left;
&.mobile { display: none } }
.content { float: right; width: 80% }
.red { background-color: red }
.blue { background-color: blue }
.green { background-color: green }
#media all and (max-width: 700px) {
.content { width: 100%; float: left }
.sidebar { display: none
&.mobile { display: block; width: 100% }
}
}
HAML
.wrapper
.sidebar.blue
.content.red
.content.green
.sidebar.mobile.blue
On 700 px page breaks, sidebar disappears and mobile sidebar appears.
This can be much more elegant but you get the picture.
Only possible downside to this approach is duplication of sidebar.
That's it, no JS.
Ok, the reason for my original question was because I couldn't find a way to move a left sidebar (which appears first in the HTML) to appear after the content on mobiles.
Despite the comments, I still can't see how using media queries and position or display alone would reliably solve the problem (perhaps someone can give an example?).
But, it did lead me to investigate the flexbox model - display: flex, and so I have ended up using that, and specifically flex's order property to re-arrange the order of the sidebars and content area.
Good guide here - https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Demonstration: http://jsfiddle.net/calvintennant/NrJ8T/show/
When I force a window resize by doing: $(window).resize() my listener is called, and everything is fine. However if I actually resize the window, I'm getting multiple resize events called within the same frame.
Timeline during forced resize:
Timeline during natural resize:
Is this a bug in Chrome, or am I misunderstanding something?
As pointed out by #avram-lavinsky, resize events can be called multiple time per frame.
Updated example using Request Animation Frame (seen first here https://developer.mozilla.org/en-US/docs/Web/Reference/Events/resize):
http://jsfiddle.net/calvintennant/v69WW/
# HTML
<div class="box-1"></div>
<div class="box-2"></div>
<div class="box-3"></div>
# CSS
html, body {
margin: 0;
}
.box-1 {
background: #00F;
bottom: 0;
position: absolute;
width: 100%;
}
.box-2 {
background: #0F0;
height: 30px;
position: relative;
}
.box-3 {
background: #F0F;
height: 66px;
position: relative;
}
# JS
var box1 = $('.box-1');
var box2 = $('.box-2');
var box3 = $('.box-3');
var drawing = false;
var resizeFired = false;
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame;
$(window).resize(function() {
// set resizedFired to true and execute drawResize if it's not already running
if (drawing === false) {
resizeFired = true;
drawResize();
}
});
function drawResize() {
var height;
// render friendly resize loop
if (resizeFired === true) {
resizeFired = false;
drawing = true;
height = $(window).height();
height -= $(box2).height();
height -= $(box3).height();
$(box1).height(height);
requestAnimationFrame(drawResize);
} else {
drawing = false;
}
}
$(window).resize();
Window resize as a user action is real-time event. It fires many times as the user drags.
I'm having a problem with the background of a pseudo-popup. I use jQuery (1.7) and this tutorial to create popups in my website. Basically I have two preformatted divs (one semi-opaque to hide the rest of the page and the other - with an image as the background - containing the actual popup, with the CSS already loaded in the page) that aren't displayed and that I show when I need them to display the popup, with additional fillings for the second div (to have different popups).
My problem is that the background of the popup doesn't load, and that I end up with only the semi-opaque background and the content of the popup. However, if disable/enable the CSS background property in the console, the background reappears as it should have in the first place.
This problem has appeared relatively recently not after any modification to the actual popup function, so I don't really know where it might come from. It can't be an issue of the background image not yet loaded since it is already there when the page has loaded.
Relevant pieces of code:
HTML:
<div id='popup_container'></div>
<div id='backgroundPopup'></div>
CSS:
#backgroundPopup{
display:none;
position: fixed;
_position:absolute; /* hack for internet explorer 6*/
height: 100%;
width: 100%;
top: 0;
left: 0;
background: #000000;
border: 1px solid #cecece;
z-index: 1;
}
#popup_container{
display: none;
position: fixed;
_position:absolute; /* hack for internet explorer 6*/
height: 526px;
width: 718px;
background: url(http://cdn.mojogroups.com/Layout/popup.png) no-repeat !important;
z-index: 2;
color: #000000;
}
Javascript:
//When initializing the page
$(document).ready(function(){
//[...]
popup = new Popup();
popup.initialize();
}
function Popup(){
var popupStatus = 0;
function togglePopup(){
if(popupStatus == 0){
centerPopup();
loadPopup();
}
else
disablePopup();
}
function loadPopup(){
if(popupStatus == 0){
$('#backgroundPopup').css({
"opacity": "0.7"
});
$('#backgroundPopup').fadeIn("fast");
$('#popup_container').fadeIn("fast");
$('body').scrollTop(0);
$('body').css('overflow', 'hidden');
popupStatus = 1;
}
}
this.disablePopup = function(){
if(popupStatus == 1){
$('#backgroundPopup').fadeOut("fast");
$('#popup_container').fadeOut("fast");
$('#popup_container').empty();
$('body').css('overflow', 'auto');
popupStatus = 0;
}
}
function centerPopup(){
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $('#popup_container').height();
var popupWidth = $('#popup_container').width();
$('#popup_container').css({
"position": "absolute",
"top": windowHeight/2 - popupHeight/2,
"left": windowWidth/2 - popupWidth/2
});
$('#backgroundPopup').css({
"height": windowHeight
});
}
this.initialize = function(){
$('#backgroundPopup').click(function(){
popup.disablePopup();
});
$(document).keypress(function(e){
if(e.keyCode==27)
popup.disablePopup();
});
}
this.contacts = function(){
//Fill the popup container...
centerPopup();
loadPopup();
popupDiv.fadeIn('fast');
}
What could it be?
Thanks in advance for your help!
EDIT: the site (early version) can be found here
UPDATE: At some point I thought it was due to the opacity attribute added by the loadPopup() function, so I removed that part of the code; but the bug still appears (although maybe less frequently, but it's hard to be sure since it was transient in the first place).
I know its not the ways to as query in answer but i we cant add images in comments so i m asking here. I have just gone through with your problem, what i m getting is you cann see the below screen shot. Is it correct output or not.