Responsive Design Using JavaScript - javascript

I am trying to make a grid add columns when enough room is available for another one. I have the code properly written to do this; but my issue is, how do I make a JavaScript event to constantly check to see if there if enough room to add a column. This is easy in CSS using media queries, but I inherited this code, and it cannot be done in CSS. So, I need a function for while a user is dragging the browser window border (to make the width larger), and inside of this function, do the responsive checking to see if a column can be added. Does this make sense? If you need more information, please let me know. Thanks very much in advance.

Bind an event listener to the window resize
window.onresize = function() {
//do your thing
}
OR the newer (won't work in IE8 or lower, use attachEvent instead)
window.addEventListener("resize", function() {
//do your thing
})

Related

How can I make my jquery if/then statement update live?

I am trying to write a simple conditional that says if div1 is displayed, then change div2's display to none. However, I want this to be updated live. So anytime div1 display is 'grid', div2 disappears from sight.
<script>
if($('.div1').css("display") == "grid") {
$('div2').css({"display":"none"});
}
</script>
What am I doing wrong here?
A block of javascript code will not just magically run whenever convenient for you, unless you make it so that it is run in such a way. What you have written will just run once, and move on. Javascript will not by itself will look for when things change.
You need to track the change and run your code after that change. If you are writing the javascript for a site, you probably know when these changes occur, so you can execute your code block when they do occur. For example if div1 changes to grid when user clicks a button, then you can bind your function to its click event so handle the situation.
A more advanced method would be to watch for changes on DOM and run a function when they occur. You can do this with MutationObservers. You can do precisely what you want, if div changes to grid, run myFunction() for example.
Another method would be to have a function run on intervals but this is an obsolete technique which is prone to errors and crashes and is by no means recommended to be used in javascript.
The $.watch plugin can do this:
$('.div1').watch('display', function() {
var display = ($(this).css('display') === 'grid' ? 'none' : 'block');
$('.div2').css('display', display);
});
Unlike the setInterval method, here's what the library does (from the github page):
This plugin lets you listen for when a CSS property, or properties, changes on element. It utilizes Mutation Observers to mimic the DOMAttrModified (Mutation Events API) and propertychange (Internet Explorer) events.
Be aware that your original code uses $('div2') instead of $('.div2') and will only match elements that look like this: <div2>foo</div2>. I've changed it to a class in my example.

How to unbind() .hover() but not .click()?

I'm creating a site using Bootstrap 3, and also using a script that makes the dropdown-menu appear on hover using the .hover() function. I'm trying to prevent this on small devices by using enquire.js. I'm trying to unbind the .hover() event on the element using this code:
$('.dropdown').unbind('mouseenter mouseleave');
This unbinds the .hover of that script but apparently it also removes the .click() event(or whatever bootstrap uses), and now when I hover or click on the element, nothing happens.
So I just want to how I can remove the .hover() on that element, that is originating from that script, but not change anything else.
Would really appreciate any help.
Thanks!
Edit: Here is how I'm calling the handlers for the hover functions:
$('.dropdown').hover(handlerIn, handlerOut);
function handlerIn(){
// mouseenter code
}
function hideMenu() {
// mouseleave code
}
I'm trying to unbind them with this code.
$('.dropdown').unbind('mouseenter', showMenu);
$('.dropdown').unbind('mouseleave', hideMenu);
But its not working.
Please help!
**Edit2: ** Based on the answer of Tieson T.:
function dropdownOnHover(){
if (window.matchMedia("(min-width: 800px)").matches) {
/* the view port is at least 800 pixels wide */
$('.dropdown').hover(handlerIn, handlerOut);
function handlerIn(){
// mouseenter code
}
function hideMenu() {
// mouseleave code
}
}
}
$(window).load(function() {
dropdownOnHover();
});
$(window).resize(function() {
dropdownOnHover();
});
The code that Tieson T. provided worked the best; however, when I resize the window, until I reach the breakpoint from any direction, the effect doesn't change. That is, if the window is loaded above 800px, the hover effect will be there, but if I make the window smaller it still remains. I tried to invoke the functions with window.load and window.resize but it is still the same.
Edit 3: I'm actually trying to create Bootstrap dropdown on hover instead of click. Here is the updated jsFiddle: http://jsfiddle.net/CR2Lw/2/
Please note: In the jsFiddle example, I could use css :hover property and set the dropdow-menu to display:block. But because the way I need to style the dropdown, there needs to be some space between the link and the dropdown (it is a must), and so I have to find a javascript solution. or a very tricky css solution, in which the there is abot 50px space between the link and the dropdown, when when the user has hovered over the link and the dropdown has appeared, the dropdown shouldn't disappear when the user tries to reach it. Hope it makes sense and thanks.
Edit 4 - First possible solution: http://jsfiddle.net/g9JJk/6/
Might be easier to selectively apply the hover, rather than try to remove it later. You can use window.matchMedia and only apply your script if the browser has a screen size that implies a desktop browser (or a largish tablet):
if (window.matchMedia("(min-width: 800px)").matches) {
/* the view port is at least 800 pixels wide */
$('.dropdown').on({
mouseenter: function () {
//stuff to do on mouse enter
},
mouseleave: function () {
//stuff to do on mouse leave
}
});
}
else{
$('.dropdown').off('mouseenter, mouseleave');
}
Since it's not 100% supported, you'd want to add a polyfill for those browsers without native support: https://github.com/paulirish/matchMedia.js/
If you're using Moderizr, that polyfill is included in that library already, so you're good-to-go.
I still don't understand how you intend to "dismiss" the dropdown-menu once it is displayed upon mousing over the dropdown element partly because there's not enough code in your question, but that's sort of irrelevant to this answer.
I think a much easier way to approach the mousenter event handling portion is not by using off()/on() to unbind/bind events at a specific breakpoints, but rather to do just do a simple check when the event is triggered. In other words, something like this:
$('.dropdown').on('mouseenter', function() {
if($('.navbar-toggle').css('display') == 'none') {
$(this).children('.dropdown-menu').show();
};
});
$('.dropdown-menu').on('click', function() {
$(this).hide();
});
Here's a working fiddle: http://jsfiddle.net/jme11/g9JJk/
Basically, in the mouseenter event I'm checking if the menu toggle is displayed, but you can check window.width() at that point instead if you prefer. In my mind, the toggle element's display value is easier to follow and it also ensures that if you change your media query breakpoints for the "collapsed" menu, the code will remain in sync without having to update the hardcoded values (e.g. 768px).
The on click to dismiss the menu doesn't need a check, as it has no detrimental effects that I can see when triggered on the "collapsed" menu dropdown.
I still don't like this from a UX perspective. I would much rather have to click to open a menu than click to close a menu that's being opened on a hover event, but maybe you have some magic plan for some other way of triggering the hide method. Maybe you are planning to register a mousemove event that checks if the mouse is anywhere within the bounds of the .dropdown + 50px + .dropdown-menu or something like that... I would really like to know how you intend to do this (curiosity is sort of killing me). Maybe you can update your code to show the final result.
EDIT: Thanks for posting your solution!

Javascript Custom Resize Event [duplicate]

This question already has answers here:
How to detect DIV's dimension changed?
(28 answers)
Closed 7 years ago.
I have a very simple question, or at least it seems that way.
I have a DIV element which will be resized at one moment. I want to be able to capture the resizing moment.
Something like this:
function myFunction(){
alert('The DIV was resized');
}
divElement.addEventListener("resize", myFunction, false);
Does anyone know the answer?
Thanks
As of December 2011, there's no built-in event to detect when a div resizes, just when a window resizes.
Check out this related question: Detecting when a div's height changes using jQuery, and this plugin from the solution to that question: http://benalman.com/projects/jquery-resize-plugin/
With jQuery resize event, you can now bind resize event handlers to
elements other than window, for super-awesome-resizing-greatness!
Why is a plugin needed for the resize event?
Long ago, the powers-that-be decided that the resize event would only
fire on the browser’s window object. Unfortunately, that means that if
you want to know when another element has resized, you need to
manually test its width and height, periodically, for changes. While
this plugin doesn’t do anything fancy internally to obviate that
approach, the interface it provides for binding the event is exactly
the same as what’s already there for window.
For all elements, an internal polling loop is started which
periodically checks for element size changes and triggers the event
when appropriate. The polling loop runs only once the event is
actually bound somewhere, and is stopped when all resize events are
unbound.
Sample Code
// You know this one already, right?
$(window).resize(function(e){
// do something when the window resizes
});
// Well, try this on for size!
$("#unicorns").resize(function(e){
// do something when #unicorns element resizes
});
// And of course, you can still use .bind with namespaces!
$("span.rainbows").bind( "resize.rainbows", function(e){
// do something when any span.rainbows element resizes
});
You can try this plugin - http://benalman.com/code/projects/jquery-resize/examples/resize/
There are various examples. Try resizing your window and see how elements inside container elements adjusted.
Example with js fiddle
In that resize() event is bound to an elements having class "test" and also to the window object and in resize callback of window object $('.test').resize() is called.
e.g.
$('#test_div').bind('resize', function(){
console.log('resized');
});
$(window).resize(function(){
$('#test_div').resize();
});
See this
My first thought is to use a custom event system. You can find a pure javascript one here ( http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/ )
After including his code, you can do something like this:
function myFunction(){
alert('The DIV was resized');
}
div_elm = document.getElmentById('div-to-resize');
EventTarget.call(div_elm);
div_elm.addListener("resize", myFunction);
Then later, just add one line to wherever you are resizing the div.
div_elm.width += 100 //or however you are resizing your div
div_elm.fire("resize");
I think that should work for you.
EDIT:
If you are not the one coding the resizing, then my first thought is something like this:
var resizeScannerInterval_id = (function(div) {
var width = div.offsetWidth;
var height = div.offsetHeight;
var interval_id = setInterval(function() {
if( div.offsetWidth != width || div.offsetHeight != height )
width = div.offsetWidth;
height = div.offsetHeight;
div.fire();
}
},250);
})(document.getElementById('div-id'))
There is a very efficient method to determine if a element's size has been changed.
http://marcj.github.io/css-element-queries/
This library has a class ResizeSensor which can be used for resize detection. It uses a event-based approach, so it's damn fast and doesn't waste CPU time.
Please do not use the jQuery onresize plugin as it uses setTimeout() loop to check for changes. THIS IS INCREDIBLY SLOW AND NOT ACCURATE.

Is it safe to call jQuery's resize() function to execute my own resize handler?

I am defining a resize handler that positions some elements on the screen, like this:
$(window).resize(function() {
// Position elements
}
I also want to execute this functionality when the page first loads, so I just add the following right after the above code:
$(window).resize();
This works just fine. However, I'm wondering if I may trigger any side effects, harmful or not, by calling this function - I really just want to execute my own resize handler. Of course, I could do the following to make sure that I execute only my handler:
var positionElements = function() {
// Position elements
}
$(window).resize(positionElements);
positionElements();
However, I'm new to JavaScript and I want to keep my code as concise as possible - this adds some boiler plate code to the mix.
Edit: In fact, my code can be shortened even more by using chaining. Like this:
$(window).resize(function() {
// Position elements
}).resize();
I cant see how it should be harmful, anything that could be triggered by a resize that is actually destructive should be avoided in the first place. What you are doing by using calling $(window).resize() is the same as the user resizing the window.
TL;DR; Yes its safe.

jQuery event to detect when element position changes

I would like to know if there is a jQuery event that I can use to determine when a particular DIV's top property has changed.
For instance, I have invisible content above a DIV. When that content becomes visible, the DIV is shifted down. I would like to capture that event and then use the offset() function to get the X/Y coordinates.
The easy answer is that there are no events in the DOM for detecting layout updates.
You have a couple options the way I see it:
Poll, nasty but it may work depending on your update frequency requirements.
Tap into whatever event causes the invisible DIV to change size and do whatever you need to do in that handler
I shall correct myself.
I took a look at the DOM and noticed the DOMAttrModified event and found this JQuery Plug-In that you might be able to leverage to do what you want.
As the article mentions, it works great in IE and Firefox but seems to have problems in WebKit.
I thiiink you should be able to do:
$(document).ready( function (){
$("#mydiv").bind("movestart", function (){ ...remember start position... });
$("#mydiv").bind("moveend", function (){ ...calculate offsets etc... });
});
$("#someId").resize(function () {
// your code
});

Categories

Resources