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
Related
Im trying to make an "Additional Comments" box on my website, which floats to the right of the page, while there's 4 inputs on the right.
For some reason, the comments box, on browser resizing, sits behind the inputs.
I want to make it so that when the browser is less than, say for example, 400px, it applies a margin to the comments box. I tried the below, but that didn't seem to work.
var browserSize = window.innerWidth();
var additional = document.getElementById("additional");
if(browserSize < 400px) {
additional.style.marginTop = "200px";
}
Could someone guide me as to where to go?
Many thanks in advance!
Why not use CSS media queries? You can do something like this in a stylesheet:
#media only screen and (max-width: 400px) {
#additional {
margin-top: 200px;
}
}
However, you should try to avoid using IDs as CSS selectors as much as possible.
Add an event listener for browser resize and a function for your work inside it:
function processResize()
{
var browserSize = window.innerWidth();
var additional = document.getElementById("additional");
if(browserSize < 400px) {
additional.style.marginTop = "200px";
}
}
window.addEventListener("resize", processResize);
Here is my site: http://stage.samkeddy.com/
It's responsive using a couple media queries and a mobile menu button powered by javascript.
Here is the javascript for the menu button:
function toggleMenu () {
if (menuIsVisible == false) {
collapsibleMenu.style.height = 'auto';
content.style.paddingTop = '290px';
menuIsVisible = true;
}
else {
collapsibleMenu.style.height = '0';
content.style.paddingTop = '80px';
menuIsVisible = false;
}
}
so you can see that I need to adjust the padding at the top of the content div, in order to offset the menu
But if resize to the mobile size, open the menu, and then resize back to the desktop size, the padding isn't fixed by the media query, because there's still an inline style from the javascript. I tried making the padding on the desktop version !important, but it the padding still doesn't change when resized, even though according to this !important beats inline.
You can test for yourself by opening the size (how it should look), resizing to a mobile width(the nav will disappear, and you will see the menu button), clicking the menu button (leave the menu open), then resize the site back to a desktop width. You will see the padding is still there. If you inspect it, you can see the original padding is crossed out in favor of the inline style.
I know this would be possible by monitoring the width with javascript and setting the padding then, but I really don't want to do that, and don't think I should have to.
EDIT: solved
First, I should have been adding classes, rather than adding CSS with my javascript.
Then I assumed that putting !important outside of a media query would make it only show up on desktop, but it took over all media queries. So placing just this in a query made it work. Note that if I was using 2 separate menus (mobile/desktop), I wouldn't need this, but since it was fixed and the #content needed padding, it had to be done. But using this technique you can also use only a single menu, but doing the height for the menu this way. I've demonstrated the technique in a codepen: http://codepen.io/anon/pen/JFvay
Adding this code to your stylesheet should solve the problem, I just tried this on your website using the Developer Tools and it's working:
#media only screen and (min-width: 643.2px) {
#content {
padding-top: 80px !important;
}
}
Although I'd strongly recommend you to create a separate navigation menu for mobile devices and resort to using #media-queries to display it.
Your problem at heart is that you're mixing CSS and in-line styles. As a general rule, avoid placing specific CSS properties directly on elements, whether in HTML, by using element.style.<property> =, or via jQuery's .css() feature. Instead, you should define the properties you want as CSS rules, using classes:
#collapsible-menu { height: auto; }
#content { padding-top: 290px; }
#someelt.menu-visible #collapsible-menu { height: 0; }
#someelt.menu-visible #content { padding-top: 80px; }
where someelt is some higher-level ancestor element. Then, your JS becomes simply
function toggleMenu() {
document.getElementById('someelt').classList.toggle('menu-visible');
}
If you are targeting browsers which do not support classList (see CanIUse), jQuery provides its own version of class toggling.
CSS is not an imperative language, but if you want, you can think of the #someelt.menu-visible part of the last two rules above as a kind of if statement: "If menus are visible, then shrink collapsible-menu to zero height", etc. In this metaphor of CSS as a kind of programming language (which it is), the presence of the menu-visible class of #someelt could be thought of as a kind of boolean "variable", I suppose. Most likely, you will no longer need a corresponding variable in your JS.
Anyway, the advantage of this is that people looking at your code can see all your CSS-related logic just by looking at the CSS file, instead of having to look at both CSS and JS, and you can change CSS-related things in just one place.
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)
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}
}
I've read many things online but I haven't found a way to make it work..
What I want:
I have a body background image and I was asked to make it a link as an advertisement.. The problem is that whatever I tried makes the whole page a link, whereas I want only the background of the webpage to act as a link. Is it possible,through html and css? Or even with use of javascript? Any solution is accepted... I'm stuck..Thanks in advance!
You can't have the background image be the link. You can use JS to catch all clicks that are on the body, but not on one of its children
// This is not cross browser, that would be a separate question
document.body.onclick = function(e) {
if (e.target === document.body) {
window.location = "link.html"
}
}
You can use jQuery for a cross browser version
$('body').click(function(e){
if (e.target === this) {
window.location = "link.html"
}
});
If you want to give the background the cursor appearance, you can apply the following CSS
body {
background-image: url(http://www.blutest.com/sites/default/files/butterfly2_large_0.jpg);
cursor: pointer;
}
body, html {
width: 100%;
height: 100%;
}
body * {
cursor: default;
}
See it in action here
Using jQuery you can detect if the event was on the body directly:
$('body').on('click', function(e) {
if( e.target != this ) return;
window.location = 'http://google.com';
});
DON'T.
This is an extremely annoying and universally hated practice. Users should be able to click on "the white" (*) without surprising effects.
I actually found your question while googling for ways to block this nasty "human exploit", and I vow to forever boycott any vendor that advertises this way.
(*) Of course the metaphorical notion of "the white" includes any area outside the main layout (or below the content of a sidebar if the sidebar is shorter than the main column) regardless of whether this area is white, solid color, or has a background image.
Nope here
keep a page division inside the body dvision
add onclick to body and onclick to page too,
in the page on click add event.stopPropagation()