Reload jquery script after resize display - javascript

I have a problem with jquery script if page size was changed. For example - if you open site on the phone, then open and close menu, then rotate phone from vertical to horizontal and open menu again - the block will not shown.
I use this script
return $(document).ready(function() {
(function($) {
if ($(window).width() < 960) {
$('#header-menu').css('display', 'none');
$('header.grid-container').css('display', 'none');
return $('#toggle-mobile-menu').click(function() {
$('#header-menu').toggle();
return $('header.grid-container').toggle();
});
}
})(jQuery);
});
I need some hook maybe, to reload script if screen was changed, without reload page. I tried to use $(window).resize() but it didn't work

It is impossible Jquery gets put into the DOM and would require a page refresh in order for the script to change.
You should consider using AJAX instead.

The problem is that your script is triggered only once after loading all DOM elements (Your are checking the screen width and if condition is done you are triggering the event). I suggest move styling to CSS (media queries) and use jquery only for binding events
CSS
#media (max-width: 960px) {
#header-menu,
.grid-container { display: none; }
#toggle-mobile-menu { display: block; } // or whatever
}
JS
$(function(){
$('#toggle-mobile-menu').on('click', function() {
$('#header-menu').toggle();
$('header.grid-container').toggle();
}
});

Related

Detecting browser width with media query using jQuery

I am trying to implement a precise way of figuring out the user's browser width based on a media query. For example, I have an element div called #check_screen initially it'll be displayed as a block element. If the browser width is < 420px, then #check_screen will have a display: none property. This is what I have tried so far:
HTML
<div id='check_screen'></div>
CSS
#check_screen{
display: block;
}
#media only screen and (max-width: 420px){
#check_screen{
display: none;
}
}
jQuery
$(document).ready(function() {
// run test on initial page load
checkSize();
// run test on resize of the window
$(window).resize(checkSize);
});
//Function to the css rule
function checkSize(){
if ($("#check_screen").css("display") == "none" ){
console.log("hello");
}
}
For some reason, it is not working correctly. When I resize the screen to < 420px, the message is not displayed to the console. I have also tried using the :visible jQuery selector, but that does not work either. I am using Chrome as my browser.
I think you have a syntax error:
$(window).resize(checkSize); should be
$(window).resize(function(){
checkSize();
});
That correction worked for me with no other changes.
Assign unvisible div and set its color to black.
If resized, change its color to green.
Javascript would be like
var check = $("element").css("background-color");
if(check == "black" {
}
else if...

JS launches before CSS

This is currently happening in chrome, in firefox I haven't had this issue (yet).
Here is a VERY simplified version of my problem.
HTML:
<div class="thumbnail">
Click me!
</div>
CSS:
div {
width: 200px;
height: 300px;
background-color: purple;
}
a {
position: absolute;
}
#media (max-width: 991px) {
div {
height: 200px;
}
}
Javascript:
$(document).ready(function () {
var $parent = $('#clickMe').parent();
function resize() {
$('#clickMe').offset({
top: $parent.offset().top + $parent.height()-$('#clickMe').height()
});
}
$(window).on('resize', resize);
resize();
});
The problem:
So what does this give when I resize (without dragging)? Well javascript launches first and sets the position of the <a></a> , then CSS applies the height change if we are < 992 px.
Logically the button is now visually at the outside of the div and not on the border like I had originally defined it to be.
Temporary solution proposed in this post.
jQuery - how to wait for the 'end' of 'resize' event and only then perform an action?
var doit;
$(window).on('resize', function(){ clearTimeout(doit); doit = setTimeout(resize, 500); });
Temporary solution is not what I'm looking for:
However, in my situation I don't really need to only call 'resize' when the resizing event is actually done. I just want my javascript to run after the css is finished loading/ or finished with it's changes. And it just feels super slow using that function to 'randomely' run the JS when the css might be finished.
The question:
Is there a solution to this? Anyone know of a technique in js to wait till css is completely done applying the modifications during a resize?
Additional Information:
Testing this in jsfiddle will most likely not give you the same outcome as I. My css file has many lines, and I'am using Twitter Bootstrap. These two take up a lot of ressources, slowing down the css application (I think, tell me if I'm wrong).
Miljan Puzović - proposed a solution by loading css files via js, and then apply js changes when the js event on css ends.
I think that these simple three steps will achieve the intended behavior (please read it carefully: I also suggest to read more about the mentioned attributes to deeply understand how it works):
Responsive and fluid layout issues should always be primarily (if not scrictly) resolved with CSS.
So, remove all of your JavaScript code.
You have positioned the inner a#clickMe element absolutely.
This means that it will be positioned within its closest relatively positioned element. By the style provided, it will be positioned within the body element, since there is no position: relative; in any other element (the default position value is static). By the script provided, it seems that it should be positioned within its direct parent container. To do so, add position: relative; to the div.thumbnail element.
By the script you provided, it seems that you need to place the a#clickMe at the bottom of div.thumbnail.
Now that we are sure that the styles added to a#clickMe is relative to div.thumbnail, just add bottom: 0px; to the a#clickMe element and it will be positioned accordingly, independently of the height that its parent has. Note that this will automatically rearrange when the window is resized (with no script needed).
The final code will be like this (see fiddle here):
JS:
/* No script needed. */
CSS:
div {
width: 200px;
height: 300px;
background-color: purple;
position: relative; //added
}
a {
position: absolute;
bottom: 0px; //added
}
#media (max-width: 991px) {
div {
height: 200px;
}
}
If you still insist on media query change detection, see these links:
http://css-tricks.com/media-query-change-detection-in-javascript-through-css-animations/
http://css-tricks.com/enquire-js-media-query-callbacks-in-javascript/
http://tylergaw.com/articles/reacting-to-media-queries-in-javascript
http://davidwalsh.name/device-state-detection-css-media-queries-javascript
Twitter Bootstrap - how to detect when media queries starts
Bootstrap: Responsitive design - execute JS when window is resized from 980px to 979px
I like your temporary solution (I did that for a similar problem before, I don't think half a second is too long for a user to wait but perhaps it is for your needs...).
Here's an alternative that you most likely have thought of but I don't see it mentioned so here it is. Why not do it all through javascript and remove your #media (max-width.... from your css?
function resize() {
var width = (window.innerWidth > 0) ? window.innerWidth : screen.width;
if(width<992){
$("div").each(function(e,obj){$(obj).height(200);});
}
$('#clickMe').offset({
top: $parent.offset().top + $parent.height()-$('#clickMe').height()
});
}
In the html page, put the link to css file in head section; next, put the link to js file just before the /body tag and see what happens. In this way css will load always before js.
Hope this help you.
Did you try to bind the resize handler not to the window but to the object you want to listen to the resize ?
Instead of
$(window).on('resize', resize);
You can try
$("#clickMe").on('resize', resize);
Or maybe
$("#clickMe").parent().on('resize', resize);
var didResize = false;
$(window).resize(function() {
didResize = true;
});
setInterval(function() {
if (didResize) {
didResize = false;
console.log('resize');
}
}, 250);
I agree with falsarella on that you should try to use only CSS to do what you are trying to do.
Anyway, if you want to do something with JS after the CSS is applied, I think you can use requestAnimationFrame, but I couldn't test it myself because I wasn't able to reproduce the behavior you explain.
From the MDN doc:
The window.requestAnimationFrame() method tells the browser that you
wish to perform an animation and requests that the browser call a
specified function to update an animation before the next repaint. The
method takes as an argument a callback to be invoked before the
repaint.
I would try something like this:
var $parent = $('#clickMe').parent();
function resize(){
$('#clickMe').offset({
top: $parent.offset().top + $parent.height()-$('#clickMe').height()
});
}
window.onresize = function(e){
window.requestAnimationFrame(resize);
}
window.requestAnimationFrame(resize);
Anyone know of a technique to wait till css is completely done loading?
what about $(window).load(function() { /* ... */ } ?
(it executes the function only when the page is fully loaded, so after css loaded)

Using jQuery .hide() with CSS media queries for menu toggle based on screen resolution

I have a website using css media queries to detect browser resolution and modify my site accordingly.
I have run into a slight problem with my main navigation menu. There are a number of pages on my site where I would like to have my main navigation hidden on load for mobile resolutions, but displayed on desktop resolutions.
This seems like a simple enough task to accomplish with css, but unfortunately for me, it is not. I am unable to use both display:none; and visibility:hidden; because when my menu detects on load that it is hidden, it sets it's height to 0, and will not change.
Here is a stack overflow page reference:
Setting a div to display:none; using javascript or jQuery
Ultimately, I the only option I found that would hide my menu on load, while still allowing the menu to correctly calculate it's height was the following bit of jQuery.
$(document).ready(function () {
$(".hide-menu").hide();
var $drillDown = $("#drilldown");
});
Now, this solution is working for pages that I would like to have the menu initially hidden on load for all screen resolutions. However, I have a number of pages on which I would like to have the menu hidden initially hidden on load for mobile, but displayed on desktop.
I have attempted to recreate this scenario in a jsfiddle: http://jsfiddle.net/WRHnL/15/
As you can see in the fiddle, the menu system has big issue with not being displayed on page load. Does anyone have any suggestions on how I might accomplish this task?
You can do it by comparing the screen-size:
$(document).ready(function () {
var width = $(window).width();
if (width < 768) {
$(".hide-menu").hide();
}
var $drillDown = $("#drilldown");
});
You can use !important to force to origional state via media queries.
This will over-ride the "display:none" from your js.
Example:
#media (max-width:980px){
nav > .btn-group{display:none}
}
Your Js then toggles style="display:block" or style="display:none"
you maximize the window and the below resets your origional style.
#media (min-width: 992px) {
nav > .btn-group{margin:0px auto; display:inline-block !important}
}

How to hide a div if it overlaps another div

Is this CSS or javascript? I just need the div to change to display:none if it comes within say 20px of another div. Thanks
Try this
https://github.com/brandonaaron/jquery-overlaps
//Listen to the event that will be triggered on window resize:
window.onresize = function(event)
{
// test if one element overlaps another
if($('#div1').overlaps('#div2'))
{
//Do stuff, like hide one of the overlapping divs
$('#div1').hide();
}
}
Based on your comment:
Yes it is so that if the user makes their browser window small my site
does not look crowded
Instead of answering the question you asked, Here's an answer to the question you didn't ask:
How to resize/position/cssify page elements based on browser size?
There is a new-ish application of css and javascript called Responsive Web Design. Responsive Design allows you to specify different css rules to apply based on different elements. For a great example of this technique, resize your browser around on The Boston Globe's website. They just integrated this technique sometime this week.
Here's an example of the css that would implement this:
#media screen and (min-width: 480px) {
.content {
float: left;
}
.social_icons {
display: none
}
// and so on...
}
example from http://thinkvitamin.com/design/beginners-guide-to-responsive-web-design/
Here is a boilerplate to get you going.
You can add an event handler that gets fired when the window is resized. You could do this with javascript or jquery. jquery makes it easy:
window.onresize = function(event) {
var h=$(window).height();
var w=$(window).width();
if(h<400 && w < 300){
//hide divs
$('#yourdivid1').hide();
}
}
Hope this helps

Hide class before document

I have about 20 tabs which are placed underneath the content (not on-top as usual) with large content (forms,inputs) on each tabs.
Problem is that when the users visit the site, they see all the content before the tabs hide. Is there a way to prevent this? I am using jQuery tabs as simple as:
$(window).load(function() {
$(".tab_content").hide();$(".tab_content:first").show();
});
I was thinking if there is a way to hide .tab_content without jQuery? So I can load jquery at the end asynchronously. I would imagine, loading jquery and then hiding tabs takes time. But yet again I was thinking that, in order to hide .tab_content you need the content so, maybe there is no way around it?
Thanks alot
the hide comes into play after the DOM is ready or the element you are applying hide is inside the DOM so a better way is to add a class that hides the element
.tab_content
{
display: none
}
and
$(function(){
$(".tab_content:first").show();
});
If you simply want to hide then you can use pure CSS:
.tab_content{
display:none;
/* or */
visibility:hidden;
}
Once your page has loaded and jQuery is ready you can then show it as required.
Use CSS to hide the tabs by default:
.tab_content { display: none; }
Show them when ready.
You can prevent showing them by default using css.
.tab_content { display: none; }
the best way is to do it in css, that way it will never show up when the page loads
.tab_content { display: none }

Categories