How to fix jQuery multiple else if statements not working - javascript

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

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

Javascript injection add item to basket

I am trying to run this script which effectively goes through a json list that contains url and a size to go to the link set add the item to cart based on size, check if it is in stock or already added. I have got the link and the size searching algorithms work independently but together they seem to not work and I can't figure out why?
var foundall = false;
var copItems = [{
"url": "https://www.supremenewyork.com/mobile/#products/303518/22745",
"size": "Medium"
}];
for (var i = 0; i < copItems.length; i++) {
AddToCart(copItems[i], function(carted) {
console.log(carted);
});
}
function AddToCart(item, callback) {
location.href = item.url;
var counter = 0;
var waitToAppear = setInterval(function() {
if (document.querySelector('#cart-update > span')) {
if (document.querySelector('#cart-update > span').innerHTML == 'remove') {
return callback("failed");
clearInterval(waitToAppear);
} else if (document.querySelector('#cart-update > span').innerHTML == 'sold out') {
copSelectSize(size, function(data) {
return callback(data);
clearInterval(waitToAppear);
});
} else if (document.querySelector('#cart-update > span').innerHTML == 'add to basket') {
copSelectSize(item.size, function(Sized) {
return callback("failed");
clearInterval(waitToAppear);
})
} else {
counter += 1;
if (counter == 5) {
return callback("failed");
clearInterval(waitToAppear);
}
}
}
}, 100);
}
function copSelectSize(size, callback) {
var counter = 0;
var checkExist = setInterval(function() {
if (document.getElementById('size-options').length) {
var sizes = document.getElementById('size-options').options;
var size_id;
for (var i = 0; i < sizes.length; i++) {
if (sizes[i].innerText == '\(Size)') {
size_id = i;
document.getElementById('size-options').selectedIndex = size_id;
document.getElementById('size-options-link').innerHTML = '\(Size)';
if (document.querySelector('#cart-update > span').innerHTML != 'remove') {
document.querySelector('#cart-update > span').click();
return callback("success");
clearInterval(checkExist);
}
var checkExista = setInterval(function() {
if (document.querySelector('#cart-update > span').innerHTML == 'remove') {
checkExista = '';
}
clearInterval(checkExista);
}, 100);
break;
}
}
}
counter += 1;
if (counter == 5) {
return callback("failed");
clearInterval(checkExist);
}
}, 200);
}

Can anyone help me correctly define a function in JS?

I have created a button with HTML and am trying to run a function I programmed with JavaScript. I cannot get the function to work and receive the error message:
reference error: myFunction is not defined
Here is my code. Can anyone help me define this function?
....<button type="button" onclick="myFunction(shot)">...
<script lang="JavaScript">
var shot = Math.random();
if (shot < .001) {
shot = 1;
} else if (shot < .18) {
shot = 2;
} else if (shot < .5) {
shot = 3;
} else if (shot < .84) {
shot = 4;
} else if (shot < .94) {
shot = 5;
} else if (shot < .991) {
shot = 6;
} else {
shot = 7;
};
function myFunction(x) {
if (x === 1) {
console.log("-2");
} else if (x === 2) {
console.log("-1");
} else if (x === 3) {
console.log("0");
} else if (x === 4) {
console.log("+1");
} else if (x === 5) {
console.log("+2");
} else if (x === 6) {
console.log("+3");
} else {
console.log("+4");
}
};
</script>
That is most likely because the script is after your <button> in your HTML. Place it above and everything should be fine.
Because your button is before your script the button doesn't know your function. When you press your button the function ins't defined yet. You have to place your script for the button.
Also it would be better to put type="text/javascript" in your <script> tag.
Your script would be like this:
<script type="text/javascript">
var shot = Math.random();
if (shot < .001) {
shot = 1;
} else if (shot < .18) {
shot = 2;
} else if (shot < .5) {
shot = 3;
} else if (shot < .84) {
shot = 4;
} else if (shot < .94) {
shot = 5;
} else if (shot < .991) {
shot = 6;
} else {
shot = 7;
};
function myFunction(x) {
if (x === 1) {
console.log("-2");
} else if (x === 2) {
console.log("-1");
} else if (x === 3) {
console.log("0");
} else if (x === 4) {
console.log("+1");
} else if (x === 5) {
console.log("+2");
} else if (x === 6) {
console.log("+3");
} else {
console.log("+4");
}
};
</script>
<button type="button" onclick="myFunction(shot)">
I'd do this using jQuery:
var shot;
$(document).ready(function () {
shot = Math.random();
if (shot < 0.001) {
shot = 1;
} else if (shot < 0.18) {
shot = 2;
} else if (shot < 0.5) {
shot = 3;
} else if (shot < 0.84) {
shot = 4;
} else if (shot < 0.94) {
shot = 5;
} else if (shot < 0.991) {
shot = 6;
} else {
shot = 7;
}
});
$("#myButton").click(function () {
var x = shot;
if (x === 1) {
console.log("-2");
} else if (x === 2) {
console.log("-1");
} else if (x === 3) {
console.log("0");
} else if (x === 4) {
console.log("+1");
} else if (x === 5) {
console.log("+2");
} else if (x === 6) {
console.log("+3");
} else {
console.log("+4");
}
});
With your button as so:
<button id="myButton" type="button">Test</button>
Demo here
With this, however, your result is going to be the same per page load unless you do the calculation for 'shot' in the click function!
I believe it is the call to your button onClick method that makes the problem.
<button type="button" onclick="myFunction(shot)">
At that point in code the shot variable is not defined.
You need to first declare the variable before usage. Or better yet remove it from button call and defined it in your myFunction as below:
<script type="text/javascript">
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getShot() {
return getRandomInt(1, 7);
}
function myFunction() {
var x = getShot();
if (x === 1) {
console.log("-2");
} else if (x === 2) {
console.log("-1");
} else if (x === 3) {
console.log("0");
} else if (x === 4) {
console.log("+1");
} else if (x === 5) {
console.log("+2");
} else if (x === 6) {
console.log("+3");
} else {
console.log("+4");
}
};
</script>
You could either put the code before the button
or
Make the script to execute after the DOM loads by using
document.addEventListener("DOMContentLoaded", function(event) {
//put your function here
});
Also, a good practice (separation of concern), is to not have have the function call on the html. Instead you could add an event listener in your javascript.
document.getElementById("myButton").addEventListener("click", function(){
// your function here
});

Javascript Condition - Not hiding ID

I'm trying to hide the ID "hide-homepage" and it's working overall, except for my second condition where I want to hide it at the stated URL (http://wgzrv.ndxva.servertrust.com/login.asp). Am I missing something?
<script type="text/javascript">
$(window).resize(function(){
function showMyDiv() {
if (window.location.href == "http://wgzrv.ndxva.servertrust.com") && (document.documentElement.clientWidth > 992) {
document.getElementById("hide-homepage").style.display="none";
} else if (window.location.href == "http://wgzrv.ndxva.servertrust.com/login.asp") {
document.getElementById("hide-homepage").style.display="none";
} else if (document.documentElement.clientWidth < 992) {
document.getElementById("hide-homepage").style.display="none";
} else {
document.getElementById("hide-homepage").style.display="block";
}
}
});
</script>
if (window.location.href == "http://wgzrv.ndxva.servertrust.com") && (document.documentElement.clientWidth > 992) {
should be
if (window.location.href == "http://wgzrv.ndxva.servertrust.com" && document.documentElement.clientWidth > 992) {
Try instead of == using indexOf()
<script type="text/javascript">
$(window).resize(function(){
function showMyDiv() {
if (window.location.href == "http://wgzrv.ndxva.servertrust.com") && (document.documentElement.clientWidth > 992) {
document.getElementById("hide-homepage").style.display="none";
} else if (window.location.href.indexOf("http://wgzrv.ndxva.servertrust.com/login.asp") > -1) {
document.getElementById("hide-homepage").style.display="none";
} else if (document.documentElement.clientWidth < 992) {
document.getElementById("hide-homepage").style.display="none";
} else {
document.getElementById("hide-homepage").style.display="block";
}
}
});
</script>
EDIT (I removed the inner function, didn't see it the first time):
<script type="text/javascript">
$(window).resize(function(){
if (window.location.href == "http://wgzrv.ndxva.servertrust.com") && (document.documentElement.clientWidth > 992) {
document.getElementById("hide-homepage").style.display="none";
} else if (window.location.href.indexOf("http://wgzrv.ndxva.servertrust.com/login.asp") > -1) {
document.getElementById("hide-homepage").style.display="none";
} else if (document.documentElement.clientWidth < 992) {
document.getElementById("hide-homepage").style.display="none";
} else {
document.getElementById("hide-homepage").style.display="block";
}
});
</script>

convert nested if statements to more elegant switch?

how can i convert this nested if statement to something more readable and 'elegant'?
if(speed==0){
othvalue=0;
}else {
if(speed>value1864cmn){
othvalue=value1864cmn;
}else {
if(speed>value1746cmn){
othvalue=value1746cmn;
}else {
if(speed>value1628cmn){
othvalue=value1628cmn;
}else {
if(speed>value1510cmn){
othvalue=value1510cmn;
}else {
if(speed>value1392cmn){
othvalue=value1392cmn;
}else {
if(speed>value1274cmn){
othvalue=value1274cmn;
}else {
if(speed>value1156cmn){
othvalue=value1156cmn;
}else {
if(speed>value1038cmn){
othvalue=value1038cmn;
}else {
if(speed>value920cmn){
othvalue=value920cmn;
}
}
}
}
}
}
}
}
}
};
You can use "match" construct:
var othvalue = (speed == 0) ? 0
: (speed <= 10) ? 10
: (speed <= 20) ? 20
: (speed <= 30) ? 30
: 40;
You don't need to nest this, nor convert it to a switch statement. Just put the if right next to the else.
For instance:
if(speed==0){
othvalue=0;
} else if(speed>value1864cmn){
othvalue=value1864cmn;
} else if {
...
if (speed == 0) {
othvalue = 0;
} else if (speed > value1864cmn) {
othvalue = value1864cmn;
} else if (speed > value1746cmn) {
othvalue = value1746cmn;
} else if (speed > value1628cmn) {
othvalue = value1628cmn;
} else if (speed > value1510cmn) {
othvalue = value1510cmn;
} else if (speed > value1392cmn) {
othvalue = value1392cmn;
} else if (speed > value1274cmn) {
othvalue = value1274cmn;
} else if (speed > value1156cmn) {
othvalue = value1156cmn;
} else if (speed > value1038cmn) {
othvalue = value1038cmn;
} else if (speed > value920cmn) {
othvalue = value920cmn;
};
if (speed == 0) {
othvalue = 0;
} else {
var values = [
value1746cmn, value1628cmn, value1510cmn, value1392cmn, value1274cmn,
value1156cmn, value1038cmn, value920cmn
];
for (var i in values) {
if (speed > values[i]) {
othvalue = values[i];
break;
}
}
}
// I don't know about elegant, but stepping through an array is pretty quick.
function setSpeedValue(speed){
var L= 9, values= [0, 920, 1038, 1156, 1274, 1392, 1510, 1628, 1746, 1864];
while(values[L]>speed)--L;
return 'value'+values[L]+'cmn';
}
alert(setSpeedValue(1040))

Categories