Dynamically Changing Class on Window Resize - javascript

What I'm doing and have spent many hours attempting today is add a class to an element when the window is resized using the value of the viewport.
Basically, I want to add the class as the viewport value in <html> on page load, then change that class as it is resized.
Page load - add value of viewport as a class to <html>
Window resize - change the class added to <html> as the viewport value
Right now I have the first part down and I have the second almost there. It will add the viewport value as a class, then when resized add the new value - but it is just adding never ending new classes and not swapping them out.
Modified code
omitted var $html = $("html");
if(typeof window.innerWidth!='undefined'){
viewportwidth=window.innerWidth
}
jQuery(window).resize(function(){
var viewportwidth;
if(typeof window.innerWidth!='undefined'){
viewportwidth=window.innerWidth;
}
jQuery("html").toggleClass(""+viewportwidth);
});
jQuery("html").addClass(""+viewportwidth);
I'm not very experienced with jQuery and JS...
Example - http://sandbox.iemajen.com/
Thanks.
Your question has been identified as a possible duplicate of another question.
Let me try to explain more clearly. I would like to have the current value of window.innerWidth returned as the only class. That is, when the window is resized, the class cycles to the next value replacing the former.
Screenshot

Try this Answer
//OnLoad:
$(document).ready(function(){
w_w = $(window).width();
if(w_w > some_value){
$("#some_id").addClass('someClass');
}
//onResize
$(window).resize(function(){
w_w = $(window).width();
if(w_w > some_value){
$("#some_id").addClass('someClass');
}
});
});

Maybe you can try something like this :
jQuery(window).resize(function(){
var viewportwidth;
if(typeof window.innerWidth!='undefined'){
viewportwidth=window.innerWidth;
}
if(viewportwidth >= 768){
$html.addClass("res_768");
}else{
$html.removeClass("res_768");
}
if(viewportwidth >= 640){
$html.addClass("res_640");
}else{
$html.removeClass("res_640");
}
//etc...
});
or
jQuery(window).resize(function(){
var viewportwidth;
if(typeof window.innerWidth!='undefined'){
viewportwidth=window.innerWidth;
}
$html.removeClass();//remove all classes
if(viewportwidth >= 768){
$html.addClass("res_768");
}
else if(viewportwidth >= 640){
$html.addClass("res_640");
}
//etc...
});

Related

How to incorporate JS media Queries and Scroll listening?

I'm currently making an element visible when my nav is at the top of the page. I'd like the element to be hidden if the page gets to max-width: 900px;. I've tried using modernizer for JS media queries but I ca't seem to get it to work.
Code:
var a = $(".menu").offset().top;
function scrollListener(){
if($(document).scrollTop() > a)
{$('.hidden-logo').css({"opacity": "1","display": "block"});
$('.menu').css({"margin-left": "-130px"})
} else {
$('.hidden-logo').css({"opacity": "0","display": "none"});
$('.menu').css({"margin-left": "0px"})
}
};
$(document).scroll(scrollListener);
You were checking the scroll position the wrong way - I think you want the logo to disappear when the current scroll is greater than the top of the logo, not less.
I added a msgS div (for demo purposes only) that will show you the current scroll value against the top-of-menu static value. I also added a 100px fudge factor to the menu location to make it more clear in the demo when the current scroll reaches that position. I use these temporary msg divs myself when working out my code, and then remove them when I've got it all sorted and ready for production.
And this is all you need to check the media query in javascript:
var winmed = window.matchMedia("(max-width: 700px)");
if (winmed.matches){ //do something }
And that can go into a listener function exactly like your scroll listener.
var gloShowLogo = true;
var a = $(".menu").offset().top;
var fudge = 100; //100px fudge factor so can SEE div disappear
function scrollListener(){
updateScrollMsg();
var currScroll = $(document).scrollTop();
var topOfMenu = a+fudge;
if( gloShowLogo && currScroll < topOfMenu ){
$('.hidden-logo').css({"opacity": "1","display": "block"});
$('.menu').css({"margin-left": "-130px"})
} else {
$('.hidden-logo').css({"opacity": "0","display": "none"});
$('.menu').css({"margin-left": "0px"})
}
};
function resizeListener(){
updateMediaMsg();
var winmed = window.matchMedia("(max-width: 500px)");
if (winmed.matches){
$('.hidden-logo').css({"opacity": "1","display": "block"});
gloShowLogo = true;
} else {
$('.hidden-logo').css({"opacity": "0","display": "none"});
gloShowLogo = false;
}
}
$(window).scroll(scrollListener);
$(window).resize(resizeListener);
function updateScrollMsg(){
$('#msgS').html( $(document).scrollTop() +' // ' + $(".menu").offset().top );
}
function updateMediaMsg(){
var winmed = window.matchMedia("(max-width: 500px)");
var medmsg = (winmed.matches) ? '< 500' : '> 500';
console.log(medmsg);
$('#msgM').html(medmsg);
}
.menu{background:green;text-align:center;}
.content{height:200vh;background:palegreen;text-align:center;}
.hidden-logo{position:fixed;top:1vh;right:1vw;padding:15px; background:pink;z-index:2;}
#msgS{position:fixed;top:0;left:0;padding:10px;background:wheat;z-index:2;}
#msgM{position:fixed;top:40px;left:0;padding:10px;background:lightblue;z-index:2;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="menu">Menu Div</div>
<div class="content">Lengthy content Div..<br><br><br><br>100<br></div>
<div class="hidden-logo">LOGO</div>
<div id="msgS"></div>
<div id="msgM"></div>
Update:
Sorry, I had the media query a bit backwards myself - I think you want the logo to display when the screen-size is < 900px and to be hidden if wider than 900px, yes?
I added a msgM div so you can watch the media query kick-in -- but getting the best width for the demo was a bit of a challenge. I finally settled at 500px as a width that can be demoed (StackOverflow resizes its StackSnippets container as the browser window resizes, which throws things into confusion at each of their resize breakpoints)

How to make an element become fixed when 50px from the top of the screen

I have a html div element that scrolls with the page but I would like it to become fixed once it reaches 50px from the top of the screen...
How is this done?
My div id is #box
Thanks!
-Ina
If you want it to be fixed at the top of the page at some distance from the top, you can check the top offset of the element and change the class when it reach the distance you want.
Here is the jquery code for your reference
jQuery(document).scroll(function() {
var documentTop = jQuery(document).scrollTop();
console.log('this is current top of your document' + documentTop );
//box top is 891
if (documentTop > 841) {
//change the value of the css at this point
jQuery("#box").addClass("stayfix");
}
else
{
jQuery("#box").removeClass("stayfix");
}
});
You need to be more specific about what have you done so far. For eg, how did you make the div element to scrolls inside the page. using css or js/jquery animation features?That will help us to give more specific answer.
**Edited According to your fiddle.
They are right, this question is duplicate. Here is a code I made with answers from the forum.
var box_top = $("#box").offset().top;
$(window).scroll(function (event) {
if ($(window).scrollTop() >= (box_top - 50)) {
$("#box").css({position:"fixed",top:"50px"});
} else {
$("#box").css({position:"relative"});
}
});
Hope it helps anyway.
https://jsfiddle.net/ay54msd5/1/
Try something like this. It's a solution using jquery (hopefully not a problem) that checks the scrollHeight of the page every time the page scrolls. If the scrollHeight is greater than a certain threshold, the element becomes fixed. If not, the element is positioned relatively (but you can do whatever you want in that case.
$(document).ready(function() {
var navFixed = false;
var $box = $("#box");
var topHeight = 50;
$(document).scroll(function() {
if ($(document).scrollTop() >= topHeight && !navFixed) {
$box.css("position", "fixed");
navFixed = true;
}
else if ($(document).scrollTop() < topHeight && navFixed) {
$box.css("position", "relative");
navFixed = false;
}
});
});
You would have to write some additional CSS targeting the #box element that tells it what coordinates you'd like it to be fixed to.

jQuery - Move element with children triggered by window resize

I have a filter on my website positioned in an aside with a class 'left-bar'. My site is responsive and i want the filter to move to the div with the class 'mobile-top-bar'.
With the first 'if' i check if the window isn't already below 992px and when that's the case the filter will be moved to the 'mobile-top-bar' (this works great)
if ($(window).width() < 992) {
$('#moveableFilter').prependTo('.mobile-top-bar');
}
With the second piece of code i've made a function that should move the filter back and forth, but that doesn't happen. The filter already disappears from the 'left-bar' when i slightly change the width of the window (when it's still above 992px) and when i change it below 992px it isn't present in the mobile-top-bar.
What did i do wrong?
$(window).on('resize', function(){
var win = $(this);
if (win.width() < 992) {
$('#moveableFilter').prependTo('.left-bar');
} else if (win.width() >= 992) {
$('#moveableFilter').prependTo('.mobile-top-bar');
}
});
It looks like you switched the cases around by accident. Try this:
$(window).on('resize', function(){
var win = $(this);
if (win.width() >= 992) {
$('#moveableFilter').prependTo('.left-bar');
} else if (win.width() < 992) {
$('#moveableFilter').prependTo('.mobile-top-bar');
}
});
... However, I do agree with the comment that says that it would be better not to use two different bars, but to move it with CSS media queries.

On window load or resize - set element property JS. Can't find error

I'm trying to set the width of a column element dynamically using js / jquery on wordpress. I'm taking this approach because my theme is hijacking my css and I have experienced an unprecedented amount of stubbornness from it.
Here is my code, I know 100% that jquery is loading and that javascript executes (by putting in alerts and testing etc.), all help appreciated!
My html is along the lines of
<div class="3-col-force">test</div>
<div class="3-col-force">test</div>
<div class="3-col-force">test</div>
<script type="text/javascript">
window.onload = fixCol();
window.onresize = fixCol();
function fixCol(){
var offset = getWidth();
if (offset > 765) {
setColumnWidth('33%');
} else {
setColumnWidth('100%');
}
}
function setColumnWidth(newWidth){
var columns = document.querySelector(".3-col-force");
columns.style.width = newWidth;
}
function getWidth() {
var width = $(window).width();
return width;
}
</script>
If you are going to use JQuery I would suggest the code below. I believe it is what your are attempting to accomplish with your code.
jsfiddle example: http://jsfiddle.net/larryjoelane/bazma5st/29/
Javascript/Jquery:
//set the limit
var limit = 765;
//the column class
var colClass = $(".3-col-force");
//window resize event
$(window).on("resize",function(){//begin on resize event
//if the window is greater than the limit
if ($(this).width() > limit) {//begin if then else
//set its width to 33%
colClass.width("33%");
} else {
//set its width to 33%
colClass.width("100%");
}//end if then else
//end of window on resize event
}).on("load",function(){//begin on load event for window load
//if the window is greater than the limit
if ($(this).width() > limit) {//begin if then else
//set its width to 33%
colClass.width("33%");
} else {
//set its width to 33%
colClass.width("100%");
}//end if then else
});//end on window load event

Check block visibility

We have code like:
<body>
<div class="blocks">some text here</div>
<div class="end"></div>
</body>
Text can fit in current browser visible part or not.
How to detect, does the block is in visible part of browser window?
I mean, if resoution is 1024x768 and .block height bigger than 768, then .end is invisible.
we should detect this on window.ready and also on browser window change.
if block is visible, then run some function.
Any help is appreciated.
Something like this:
$.fn.viewport = (function() {
var vp = function(el, opts){
this.el = $(el);
this.opts = opts;
this.bind(); // bind resize and scroll
this.change(); // init change
};
vp.prototype = {
bind: function(){
$(window).bind('resize scroll',
$.proxy(this.change, this));
},
change: function(e){
var p = this.el.position(),
o = this.el.offset(),
d = { w: this.el.width() +o.left, h: this.el.height()+o.top },
win = $(window),
winD = {w:win.width() + win.scrollLeft(), h:win.height()+win.scrollTop()};
if(d.w <= winD.w && d.h <= winD.h){
console.log('inview');
} else {
console.log('out of view');
this.opts.outOfView.call(this);
}
}
};
return function(opts){
return $(this).each(function(){
$(this).data('vp', new vp(this, opts));
});
};
})();
And use like this:
$('#el').viewport({
outOfView: function(){
alert('out of view');
}
});
First grab the window dimensions.
var windowSize = {width: $(window).width(), height: $(window).height() + $(window).scrollTop()};
Next grab the div position in relation to the document:
var position = $('.block').offset()
Then make your if's:
if(position.top > windowSize.height){ /* here we go */ }
You might want to also grab div dimensions in case there is a possibility it will be out of bounds on the top or left side.
You could make it into a function that returns a boolean value and then call it on the window.resize and document.ready events.
EDIT: Added scrollTop to account for scrolling.
As a quick answer you'll have to do some computation on load (psuedocode assumes jQuery).
Find the window height $(window).outerHeight(true)
Find the offset of the ".end" element $(".end").offset()
Find the scroll distance of the window $(window).scrollTop()
Calculate! It should roughly be:
if ((step1 + step3) > step2) {
//do stuff here
}
Note that that does not check if you are scrolled past the ".end" element. I didn't verify this one, so hopefully I'm not missing something big.
Get the offsetTop and offsetLeft attributes of the element
Get the width of the element in question
Get the width of screen
Do the relevant maths and see if the element is in the viewport or now.
in jQuery you can do something like
$("#element").attr("offsetTop")
EDIT:
Simple and Effective: http://jsfiddle.net/hPjbh/

Categories

Resources