Add class to html depending on screen size - javascript

When a screen size is smaller than x-amount of pixels, the HTML should get a class if it is bigger and smaller than an x-amount it should get a different class and so on.
I am using jQuery 2.2.1.
JavaScript
$(document).on('resize, ready', function() {
// Add class if screen size equals
var $window = $(window),
$html = $('html');
function resize() {
if ($window.width() < 768) {
return $html.addClass('xs');
}
else if ($window.width() > 768 && $window.width() < 992) {
return $html.addClass('sm');
}
else if ($window.width() > 992 && $window.width() < 1200) {
return $html.addClass('md');
}
else if ($window.width() > 1200) {
return $html.addClass('lg');
}
$html.removeClass('xs sm md lg');
}
$window.resize(resize).trigger('resize');
});
The problem is, that on page load, it will get the correct class, when resizing the browser the correct class will add, but it won't remove the old class.
http://jsbin.com/jusapucadi/edit?html,js,output
I am using the code from this post:
jquery, add/remove class when window width changes

Your code doesn't work as you return before removing the old class.
Change it like this, by remove the old class before setting the new.
$(document).on('resize, ready', function() {
// Add class if screen size equals
var $window = $(window),
$html = $('html');
function resize() {
$html.removeClass('xs sm md lg');
if ($window.width() < 768) {
return $html.addClass('xs');
}
else if ($window.width() > 768 && $window.width() < 992) {
return $html.addClass('sm');
}
else if ($window.width() > 992 && $window.width() < 1200) {
return $html.addClass('md');
}
else if ($window.width() > 1200) {
return $html.addClass('lg');
}
}
$window.resize(resize).trigger('resize');
});

I think you should remove old class in start of the method and remove each class like this:
function resize() {
$html.removeClass('xs sm md lg');
if ($window.width() < 768) {
return $html.addClass('xs');
}
else if ($window.width() > 768 && $window.width() < 992) {
return $html.addClass('sm');
}
else if ($window.width() > 992 && $window.width() < 1200) {
return $html.addClass('md');
}
else if ($window.width() > 1200) {
return $html.addClass('lg');
}
}
or you can set class attribute to ""
$html.attr("class","");

Use jquery .attr and it automatically removes the other classes , from Jquery
To replace all existing classes with another class, we can use .attr( "class", "newClass" ) instead.
$(document).on('resize, ready', function() {
// Add class if screen size equals
var $window = $(window),
$html = $('html');
function resize() {
if ($window.width() < 768) {
return $html.attr( "class","xs" );
}
else if ($window.width() > 768 && $window.width() < 992) {
return $html.attr( "class", "sm" );
}
else if ($window.width() > 992 && $window.width() < 1200) {
return $html.attr( "class", "md" );
}
else if ($window.width() > 1200) {
return $html.attr( "class", "lg" );
}
}
$window.resize(resize).trigger('resize');
});
.xs body {
background:red;
}
.sm body {
background:blue;
}
.md body {
background:black;
}
.lg body {
background:purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
</body>
</html>
updated jsbin

/* cache object */
$html = $('html');
$(document).on('resize, ready', function() {
/* initially remove all existing classes */
$html.removeClass('xs sm md lg');
var width = $(window).width();
if (width < 768) {
return $html.addClass('xs');
}else if (width > 768 && width < 992) {
return $html.addClass('sm');
}else if (width > 992 && width < 1200) {
return $html.addClass('md');
}else{
return $html.addClass('lg');
}
});

Related

How to fix jQuery multiple else if statements not working

I am trying to run this function but it doesn't reach the first else if when I reach the specified screen size, it will continue to use the first if.
$(window).resize(function() {
function removeClass() {
$('#cookbook_add').removeClass('st-remove-label');
$('#email_page').removeClass('st-remove-label');
}
function addClass() {
$('#cookbook_add').addClass('st-remove-label');
$('#email_page').addClass('st-remove-label');
}
function addRemoveLabel() {
lastWidth = $(window).width();
if (lastWidth < 1150) {
console.log('1150');
addClass();
} else if (lastWidth < 975) {
console.log('975');
removeClass();
} else if (lastWidth < 680) {
console.log('680');
addClass();
} else {
removeClass();
}
}
addRemoveLabel();
});
I expect the console logs to fire when the screen is that size, but it doesn't.
You should specify a range greater than and lower than for each of the if statements
$(window).resize(function() {
function removeClass() {
$('#cookbook_add').removeClass('st-remove-label');
$('#email_page').removeClass('st-remove-label');
}
function addClass() {
$('#cookbook_add').addClass('st-remove-label');
$('#email_page').addClass('st-remove-label');
}
function addRemoveLabel() {
lastWidth = $(window).width();
if (lastWidth < 1150 && lastWidth > 975) {
console.log('1150');
addClass();
} else if (lastWidth < 975 && lastWidth > 680) {
console.log('975');
removeClass();
} else if (lastWidth < 680) {
console.log('680');
addClass();
} else {
removeClass();
}
}
addRemoveLabel();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
JSFiddle: https://jsfiddle.net/on0pet6g/
The problem is that the first if will be reached with any number < 1150... so 975 is < than 1150, 680 is < than 1150.
The best way is to compare the lowest values first like that:
if (lastWidth < 680) {
console.log('680');
addClass();
}
else if (lastWidth < 975) {
console.log('975');
removeClass();
}
else if (lastWidth < 1150) {
console.log('1150');
addClass();
}
else {
removeClass();
}
Just change the order.
Change the function to
function addRemoveLabel() {
lastWidth = $(window).width();
if (lastWidth <= 1150 && lastWidth > 975) {
console.log('1150');
addClass();
} else if (lastWidth <= 975 &&lastWidth > 680) {
console.log('975');
removeClass();
} else if (lastWidth <= 680) {
console.log('680');
addClass();
} else {
removeClass();
}
}

Creating multiple if/else conditions using javascript

I'm having an issue on how I can set multiple conditions. Basically I have three conditions that would read or listen to browser viewport. The first and second conditions are working but the third condition doesn't seem to trigger. Is it because of the conflict with the second condition?
if($(window).width() > 1280) {
console.log('desktop');
}
else if ($(window).width() < 1280) {
console.log('tablet');
}
else if ($(window).width() < 780) {
console.log('mobile');
}
It is because of your second else/if. If $(window).width() is less than 780, it is also less than 1280
Change it to
else if ( $(window).width() >= 780 && $(window).width() < 1280) {
console.log('tablet');
}
Your second condition also includes the third one. Because every value which is below 780 is also below 1280. You need something like windowWidth < 1280 && windowWidth >= 780 to give the range.
const windowWidth = $(window).width();
if(windowWidth > 1280) {
console.log('desktop');
} else if (windowWidth < 1280 && windowWidth >= 780 ) {
console.log('tablet');
} else if (windowWidth < 780) {
console.log('mobile');
}
Also it will be good to keep the window into a variable, not every time use with jQuery.
Here is a more concise example, but the condition rely on the order, some people do not like this style, but I think it is OK, and we can add a comment.
//Do not change the condition order
if($(window).width() <= 780) {
console.log('mobile');
}
else if ($(window).width() <= 1280) {
console.log('tablet');
}
else {
console.log('desktop');
}
Edited: The condition should be * than and equal to ....
There is flaw in your second condition...below is the fix..hope it helps!!
if($(window).width() > 1280) {
console.log('desktop');
}
else if ($(window).width() < 1280 && $(window).width() >= 780) {
console.log('tablet');
}
else if ($(window).width() < 780) {
console.log('mobile');
}
It's because the condition before < 780 is also met (ie. If the width is equal to 600 its inferior to 1280). Change the condition order or, better, improve the second condition :
if($(window).width() >= 1280) {
console.log('desktop');
}
else if ($(window).width() < 1280 && $(window).width() >= 780) {
console.log('tablet');
}
else if ($(window).width() < 780) {
console.log('mobile');
}
You also forgot a case, if the user's screen resolution is equal to 1280, you'll never enter any of your conditions. I change > to >= to include that case.
you can try this also, it will satisfy your second condition
if ($(window).width() > 1280) {
console.log('desktop');
}
else if ($(window).width() < 1280) {
if ($(window).width() < 780) {
console.log('mobile');
} else {
console.log('tablet');
}
}
or
if ($(window).width() > 1280) {
console.log('desktop');
}
else {
if ($(window).width() < 780) {
console.log('mobile');
} else {
console.log('tablet');
}
}
The correct way to do this would be to move your third condition up to the second spot.
When doing this kind of checks always place the most restricting condition first.
In your case, the tidiest way is:
var w = $(window).width();
if (w < 780) { // most restrictive condition. Excludes all the others...
console.log('mobile');
} else if (w < 1280) { // this one includes the one above but it will never be triggered if w < 780
console.log('tablet');
} else { // all the other cases
console.log('desktop');
}
Contrary to what many said, there is no need for this else if statement:
else if (windowWidth < 1280 && windowWidth >= 780) { ... }
This adds an unnecessary, redundant check.
It sure is a light operation, but imagine that, instead of windowWidth < 1280 you were checking
functionForCalculatingWidth() : int {
// huge amount of lines with expensive computation
return result;
}
you would be calling the same function twice. See why it is bad design?
In the same way, if you were to check conditions based on the largest element (plus let's add another fictional condition), you would do:
var w = $(window).width();
if (w > 1280) {
console.log('desktop');
} else if (w > 990) {
console.log('weird device');
} else if (w > 780) {
console.log('tablet');
} else {
console.log('mobile');
}
Hope this will satisfy you you can check this.
Different is this shows width in console easy to understand this logic if you cant understand let me know
Here is fiddle
$(window).bind("resize", function() {
sizewindow = $(this).width();
console.log(sizewindow)
if (sizewindow < 780) {
console.log('mobile');
} else if (780 < sizewindow < 1280) {
console.log('szechuan sauce');
if (sizewindow > 1280) {
console.log('rick and morty gone for 2 years sad af')
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

jQuery page scroll event logic -- how to throttle

I have some jQuery listeners setup as follows:
$(document).scroll(function() {
if( $(this).scrollTop() < change1) {
updateBarChart('valuem', 'opencomparison');
} else if ( $(this).scrollTop() > change1 && $(this).scrollTop() < change2) {
updateBarChart('valuef', 'opencomparison');
} else if ($(this).scrollTop() > change2) {
updateBarChart('valuem', 'remove')
//updateSteamChart('','steam')
}
});
Straightforward enough. Some charts are updated when scrolling changes.
My issue is, this is sending too many function updates. I'd like if there were a way to throttle the .scroll(function() {}) That way, fewer event updates are fired.
Ideas?
A fairly simple way of achieving throttling might be to add a check against a random value so that it only fires a certain percentage of the time:
$(document).scroll(function() {
//Only fires 10% of the time
if (Math.random() < 0.1) {
if( $(this).scrollTop() < change1) {
updateBarChart('valuem', 'opencomparison');
} else if ( $(this).scrollTop() > change1 && $(this).scrollTop() < change2) {
updateBarChart('valuef', 'opencomparison');
} else if ($(this).scrollTop() > change2) {
updateBarChart('valuem', 'remove');
}
}
});
Alternatively, you could use a timer so that it only fires once per x miliseconds:
$(document).scroll(function() {
//Only fires at most once every half-second
if (timer > 500) {
timer = 0;
if( $(this).scrollTop() < change1) {
updateBarChart('valuem', 'opencomparison');
} else if ( $(this).scrollTop() > change1 && $(this).scrollTop() < change2) {
updateBarChart('valuef', 'opencomparison');
} else if ($(this).scrollTop() > change2) {
updateBarChart('valuem', 'remove');
}
}
});
var timer = 0;
setInterval(function () { timer += 50; }, 50);

Jquery - Detect Window Width

i have this little script where i try to detect the window size to apply the limit of caracters of an element.
the problem the detection is not working. Always apply the limit of 150.
i have set an alert to look if detect or not, and now i´m sure that he is always apply the same.
can someone help me to find out what is wrong with this script?
here is my code:
$(function () {
$(".block6 p").each(function (i) {
len = $(this).text().length;
if (len > 10) {
if ($(window).width() <= 1280) {
$(this).text($(this).text().substr(0, 150) + '...');
}
else if ($(window).width() > 1280) {
$(this).text($(this).text().substr(0, 10) + '...');
}
}
});
});
Your code only runs once, on document.ready. You need to run the test every time the window is resized:
$(window).on('resize',function() {
if ($(window).width() <= 1280) {
$(".block6 p").each(function (i) {
var len = $(this).text().length;
if (len > 10) {
$(this).text($(this).text().substr(0, 150) + '...');
}
});
} else { //if ($(window).width() > 1280) {
$(".block6 p").each(function (i) {
var len = $(this).text().length;
if (len > 10) {
$(this).text($(this).text().substr(0, 10) + '...');
}
});
}
});
$(document).ready(function() {
$(window).trigger('resize');
}
http://jsfiddle.net/mblase75/6PQ4Q/
That said, you have a problem in that you're altering the text of each element directly, so switching back and forth by resizing the browser will be destructive. I suggest using text-overflow: ellipsis instead if possible.

prototype: show a element when scroll page pased 800px

If user up, then hide the element. A div.
i have something:
<script>
window.onscroll = function()
{
if (document.documentElement.scrollTop > 900 || self.pageYOffset > 900) {
$('#divId').css('display','block');
} else if (document.documentElement.scrollTop < 900 || self.pageYOffset < 900) {
$('#divId').css('display','none');
}
}
</script>
But not work.
Something like this:
$(window).scroll(function () {
var $someDiv = $("#someDiv"),
top = $(this).scrollTop();
if (top > 200) {
$someDiv.show();
} else {
$someDiv.hide();
}
});​
See this Fiddle.

Categories