Creating multiple if/else conditions using javascript - 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>

Related

Why doesn't this JS work? (window.scrollTop)

The class 'stuck-sm' is added, but 'stuck-md' is not.
if ($(window).scrollTop() >= 285) {
$('.something').addClass('stuck-sm');
} else if ($(window).scrollTop() >= 430) {
$('.something').addClass('stuck-md');
} else {
$('.something').removeClass('stuck-sm','stuck-md');
}
else if is reachable only if the value is less than 285 which means second else if block won't get execute. Below is the correct solution.
if ($(window).scrollTop() >= 430) {
$('.something').addClass('stuck-md');
} else if ($(window).scrollTop() >= 285) {
$('.something').addClass('stuck-sm');
} else {
$('.something').removeClass('stuck-sm','stuck-md');
}

Add class to html depending on screen size

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');
}
});

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);

scrollTop not working with 2 operators

So basically I am just trying to change the CSS class of a specific element upon scrolling. This worked great when using this code:
$(window).bind('scroll', function() {
if ($(window).scrollTop() >= 270) {
$('.homeLink').addClass('selected');
}
else {
$('.homeLink').removeClass('selected');
}
});
However, I want to remove the class upon scrolling further. So I tried using this code:
$(window).bind('scroll', function() {
if ($(window).scrollTop() >= 270 && < 300) {
$('.homeLink').addClass('selected');
}
else {
$('.homeLink').removeClass('selected');
}
});
When using the 2nd code, it just doesn't work at all. Meaning, nothing changes.
I know I am just being stupid and doing this wrong, but I am not sure how to fix it. I am pretty big noob when it comes to js. Any help would be very appreciated.
EDIT:
I have also tried this with no luck:
$(window).bind('scroll', function() {
if ($(window).scrollTop() >= 270 && $(window).scrollTop() < 300) {
$('.homeLink').addClass('selected');
}
else {
$('.homeLink').removeClass('selected');
}
});
This is the correct sintax:
if ($(window).scrollTop() >= 270 && $(window).scrollTop() < 300) {
Try this:
if($(this).scrollTop()>= 270 && $(this).scrollTop() < 300){

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.

Categories