I need to conditionally change the background of div based on the value of a variable here is my code:
<script type="text/javascript">
$(document).ready(function(){
if (combo.hcs <= 10) && (combo.hcs >= 1)
$(".myClass").css("background-image", "url('BB.png')";
else if (combo.hcs <= 20) && (combo.hcs >= 11)
$(".myClass").css("background-image", "url('BH.png')";
else if (combo.hcs <= 30) && (combo.hcs >= 21)
$(".myClass").css("background-image", "url('BM.png')";
else if (combo.hcs <= 40) && (combo.hcs >= 31)
$(".myClass").css("background-image", "url('HB.png')";
else if (combo.hcs <= 50) && (combo.hcs >= 41)
$(".myClass").css("background-image", "url('HH.png')";
else if (combo.hcs <= 60) && (combo.hcs >= 51)
$(".myClass").css("background-image", "url('HM.png')";
else if (combo.hcs <= 70) && (combo.hcs >= 61)
$(".myClass").css("background-image", "url('MB.pmg')";
else if (combo.hcs <= 80) && (combo.hcs >= 71)
$(".myClass").css("background-image", "url('MH.png')";
else if (combo.hcs <= 99) && (combo.hcs >= 81)
$(".myClass").css("background-image", "url('MM.png')";
}
</script>
I am not sure if this is the best approach or not but ether way, I am getting the following error in Chrome:
Uncaught SyntaxError: Unexpected token &&
I think my approach would be to save the background-urls in an array.
var imgs = ['BB.png','BH.png']; // etc in right order
var myIndex = Math.floor(combo.hcs/10);
$(".myClass").css("background-image", "url(" + imgs[myIndex] + ")");
With this solution you would not need the if/else statements. For every tenth, you store an img-name in the array.
Consider a switch statement and a more concise approach to remain DRYer and cleaner:
var bg;
var x = combo.hcs;
switch (true) {
case (x>0 && x<=10):
bg = "BB";
break;
case (x>10 && x<=20):
bg = "BH";
break;
// etc....
}
$(".myClass").css("background-image", "url('" + bg + ".png'");
If you ask for a different solution, I would actually do it in a generic way. I would name images like 10.png, 20png, 30.png... 100.png
and then would load them something like this:
var imageName = Math.ceil(combo.hcs/10)*10
var imageFullName = imageName+'.png'
$(".myClass").css("background-image", "url('"+imageFullName+"')";
you will edit it but I hope you got the point, this has only 3 lines. You can also add conditions for boundary dimensions.
And about your error:
your code
if (combo.hcs <= 10) && (combo.hcs >= 1)
should be like this:
if ((combo.hcs <= 10) && (combo.hcs >= 1))
You shouldn't be closing the brackets. The brackets enclose the condition:
if (combo.hcs <= 10 && combo.hcs >= 1)
$(".myClass").css("background-image", "url('BB.png')";
You need to include your two conditions inside the same brackets, like this :
else if (combo.hcs <= 99 && combo.hcs >= 81)
The complete corrected code :
<script type="text/javascript">
$(document).ready(function(){
if (combo.hcs <= 10 && combo.hcs >= 1)
$(".myClass").css("background-image", "url('BB.png')");
else if (combo.hcs <= 20 && combo.hcs >= 11)
$(".myClass").css("background-image", "url('BH.png')");
else if (combo.hcs <= 30 && combo.hcs >= 21)
$(".myClass").css("background-image", "url('BM.png')");
else if (combo.hcs <= 40 && combo.hcs >= 31)
$(".myClass").css("background-image", "url('HB.png')");
else if (combo.hcs <= 50 && combo.hcs >= 41)
$(".myClass").css("background-image", "url('HH.png')");
else if (combo.hcs <= 60 && combo.hcs >= 51)
$(".myClass").css("background-image", "url('HM.png')");
else if (combo.hcs <= 70 && combo.hcs >= 61)
$(".myClass").css("background-image", "url('MB.pmg')");
else if (combo.hcs <= 80 && combo.hcs >= 71)
$(".myClass").css("background-image", "url('MH.png')");
else if (combo.hcs <= 99 && combo.hcs >= 81)
$(".myClass").css("background-image", "url('MM.png')");
}
</script>
Related
I am making an if statement that executes using variables based on the Date() function, but the if statement doesn't appear to prevent execution when it should. The code block is intended to reveal one among a set of possible paragraphs when the time is right. Here is my script
<script>
const D = new Date();
var m = D.getMinutes();
var h = D.getHours();
function showMessage() {
if ((0 < h <= 5) || ((h == 6) && (m == 0))) {
document.getElementById("m1").classList.remove("message");
} else if (((6 == h) && (m != 0)) || (6 < h < 12) || ((h == 12) && (m == 0))) {
document.getElementById("m2").classList.remove("message");
} else if (((12 == h) && (m != 0)) || (12 < h < 18) || ((h == 18) && (m == 0))) {
document.getElementById("m3").classList.remove("message");
} else {
document.getElementById("m4").classList.remove("message");
}
}
showMessage();
</script>
Here is the relevant HTML block:
<div id="messagecontainer">
<p class="message" id="m1">Good morning, you must be an early bird!</p>
<p class="message" id="m2">Good morning</p>
<p class="message" id="m3">Good afternoon</p>
<p class="message" id="m4">Good evening</p>
</div>
And here is the CSS that makes it work:
.message {
display: none;
}
As you can see, when the "message" class is removed from any paragraph, the paragraph should be revealed. I know this part works but the problem is that, it's always revealing the id="m1" paragraph when it shouldn't be. It should only be excuting from 1am (this is a mistake I just noticed and will fix) to 6pm. Otherwise it should go to as many else if statements as necessary until the time is right and the correct text block executes. For example, it is 3:30pm (15h30m) now and therefore the third block with the "m3" paragraph should be showing. But it's still the "m1".
The only things I can think of are that I somehow botched the syntax on the if statements or otherwise the variable scope isn't allowing me access to the variables within the if statements (I believe they should be global but I could be wrong). Can anyone see the problem?
This doesn't do what you think it does:
(0 < h <= 5)
This will evaluate one of the conditions first, then use the result of that condition to evaluate the second one. So you're essentially doing this:
(false <= 5)
Which would be true.
Separate the logical conditions explicitly:
((0 < h) && (h <= 5))
You are writing some conditions that don't work as expected (they work in mathematical notation, but not when writing code).
Take this for example 0 < h <= 5. It will get executed in steps
0 < 5. This can either be true or false
true < 5 or false < 5, both of which will end up being evaluated to true. This is because of how JS converts some values when doing boolean or math operations
You need to split all of this in something like this 0 < h && h <= 5
The first if statement will always result to true
(0 < h <= 5) is equal to ((0 < h) <= 5) and you can check that it will be always true
In JavaScript, to check if a number is between two numbers (what in regular math would be n1 < x < n2), you have to use the && operator
(0 < h) && (h <= 5)
so:
(0 < h <= 5) || ((h == 6) && (m == 0)) is equal to
((0 < h) <= 5) || ((h == 6) && (m == 0))
which is not what you intended because the first two parenthesis will always result in a true value.
What you want is that:
((0 < h) && (h <= 5)) || ((h == 6) && (m == 0))
I would suggest a simplification of the conditional using a ternary and the use the "value" defined as a class and just do it there.
Alternative: toggle with a data attribute (second example)
function showMessage() {
const now = new Date();
const m = now.getMinutes();
const h = now.getHours();
let test = (h <= 5 || (h == 6 && m == 0)) ? "am" :
((h >= 6 && h < 12) || (h == 12 && m == 0)) ? "morning" :
((h >= 12 && m > 0) || (h > 12 && h < 18) || (h == 18 && m == 0)) ? "afternoon" :
"evening";
document.querySelector('.' + test)
.classList.remove("message");
}
showMessage();
.message {
display: none;
}
<div id="messagecontainer">
<p class="message am" id="m1">Good morning, you must be an early bird!</p>
<p class="message morning" id="m2">Good morning</p>
<p class="message afternoon" id="m3">Good afternoon</p>
<p class="message evening" id="m4">Good evening</p>
</div>
Alternate:
function showMessage() {
const now = new Date();
const m = now.getMinutes();
const h = now.getHours();
let test = (h <= 5 || (h == 6 && m == 0)) ? "am" :
((h >= 6 && h < 12) || (h == 12 && m == 0)) ? "morning" :
((h >= 12 && m > 0) || (h > 12 && h < 18) || (h == 18 && m == 0)) ? "afternoon" :
"evening";
document.querySelector('.' + test)
.dataset.toggle = "show";
}
showMessage();
.message {
display: none;
}
.message[data-toggle="show"] {
display: block;
}
<div id="messagecontainer">
<p class="message am">Good morning, you must be an early bird!</p>
<p class="message morning">Good morning</p>
<p class="message afternoon">Good afternoon</p>
<p class="message evening">Good evening</p>
</div>
I don't think there's any such method in the DOM API like element.doesOverlap(otherElement), so I think I have to calculate this by hand, right? Not sure if there are any shortcuts.
If not, what is the method for this? It seems like there's so many ways something could overlap....it would be so many conditionals. Is there a concise way of writing this?
In pseudo code, I have this:
if (
((A.top < B.bottom && A.top >= B.top)
|| (A.bottom > B.top && A.bottom <= B.bottom))
&&
((A.left < B.right && A.left >= B.left)
|| (A.right > B.left && A.right <= B.right))) {
// elements A and B do overlap
}
^Is this the simplest way?
This is essentially and x,y comparison problem. You essentially need to compare the two element by there x,y positions at all boundaries ( top, right, bottom and left ) if they overlap anywhere.
A simple method would be, to test that they don't overlap.
Two items could be considered to overlap if none of the following are true:
- box1.right < box2.left // too far left
- box1.left > box2.right // too far right
- box1.bottom < box2.top // too far above
- box1.top > box2.bottom // too far below
Only really a slight change to what you had.
function checkOverlap(elm1, elm2) {
e1 = elm1.getBoundingClientRect();
e2 = elm2.getBoundingClientRect();
return e1.x <= e2.x && e2.x < e1.x + e1.width &&
e1.y <= e2.y && e2.y < e1.y + e1.height;
}
window.onload = function() {
var a = document.getElementById('a');
var b = document.getElementById('b');
var c = document.getElementById('c');
console.log("a & b: "+checkOverlap(a,b));
console.log("a & c: "+checkOverlap(a,c));
console.log("b & c: "+checkOverlap(b,c));
}
<div id="a" style="width:120px;height:120px;background:rgba(12,21,12,0.5)">a</div>
<div id="b" style="position:relative;top:-30px;width:120px;height:120px;background:rgba(121,211,121,0.5)">b</div>
<div id="c" style="position:relative;top:-240px;left:120px;width:120px;height:120px;background:rgba(211,211,121,0.5)">c</div>
There isn't an easier way. The correct code is this, covering all possible ways two elements can overlap:
const doElementsOverlap = (elementA: any, elementB: any) => {
const A = elementA.getBoundingClientRect();
const B = elementB.getBoundingClientRect();
return (
((A.top < B.bottom && A.top >= B.top)
|| (A.bottom > B.top && A.bottom <= B.bottom)
|| (A.bottom >= B.bottom && A.top <= B.top))
&&
((A.left < B.right && A.left >= B.left)
|| (A.right > B.left && A.right <= B.right)
|| (A.left < B.left && A.right > B.right))
);
};
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
Good afternoon,
The code below should represent the FizzBuzz game.
for (var i = 0, i < 100, i++) {
if(((i % 3) == 0) && ((i % 5) = 0)) {document.write('FizzBuzz')}
else if( ((i % 3) == 0) && ((i % 5) != 0)) {document.write('Fizz')}
else if( (( i % 3 ) != 0) && ((i % 5) == 0) ) {document.write('Buzz')}
else {document.write(i)}
}
This is the error I got in Mozilla Firefox Debugger
SyntaxError: missing ; after for-loop initialize 1.18.
I'm stuck.
There are two possible mistakes
1) Inside for loop conditional statement it should be ; but ,
2) There is a invalid left side assignment at ((i % 5) = 0), it should be ((i % 5) == 0)
To debug such issue use any linter and properly indent the code
for (var i = 0; i < 100; i++) {
if (((i % 3) == 0) && ((i % 5) == 0)) {
document.write('FizzBuzz')
} else if (((i % 3) == 0) && ((i % 5) != 0)) {
document.write('Fizz')
} else if (((i % 3) != 0) && ((i % 5) == 0)) {
document.write('Buzz')
} else {
document.write(i)
}
}
DEMO
You should use semi colons instead of commas in your loop:
for (var i = 0; i < 100; i++)
{
if ( i % 3 == 0 && i % 5 == 0 ) {document.write('FizzBuzz')}
else if ( i % 3 == 0 && i % 5 != 0 ) {document.write('Fizz')}
else if ( i % 3 != 0 && i % 5 == 0 ) {document.write('Buzz')}
else {document.write(i)}
}
You also have a massive parentheses overload! You don't need that many parens, they were also causing you errors.
So I made this code awhile ago, and it worked then, but now it won't. Can someone tell me what's wrong? What the code does is simple: I take a weapon damage value from a Fallout game (averaging the value first if FO1/FO2/FOT), tell it what game it's from, and it outputs how much damage it does in d20 Modern. I don't know if explaining what it does helps, but I hope it's clear.
var systemSelect = prompt("What system are you using? FO, F2, FT, F3, or FNV?")
var damage = parseInt(prompt("How much damage does the weapon do?"))
if (systemSelect === "FO" or "F2" or "FT") {
if (damage >= 1 && < 11) {
damage = "2d4";
} else if (damage >= 11 && < 26) {
damage = "2d6";
} else if (damage >= 26 && < 46) {
damage = "2d8";
} else if (damage >= 46 && < 61) {
damage = "2d10";
} else if (damage >= 61 && < 81) {
damage = "2d12";
} else if (damage >= 81 && < 101) {
damage = "4d6";
} else {
damage = "2d20";
}
}
if (systemSelect === "F3" or "FNV") {
if (damage >= 1 && < 8) {
damage = "2d4";
} else if (damage >= 8 && < 15) {
damage = "2d6";
} else if (damage >= 15 && < 25) {
damage = "2d8";
} else if (damage >= 25 && < 37) {
damage = "2d10";
} else if (damage >= 37 && < 61) {
damage = "2d12";
} else if (damage >= 61 && < 81) {
damage = "4d6";
} else {
damage = "2d20";
}
}
Your problem seems to be bad syntax in your if-conditions.
First of all, you can't say if (damage >= 1 && < 11), you need to specify the variable in each condition, i.e. if (damage >= 1 && damage < 11).
Secondly, the "or" operator is not or, it's || so you need if (systemSelect=="FO" || systemSelect=="F2" || systemSelect=="FT")
Fix those problems and try again - good luck :)
I want some script for my app to change the font-size of a title depending on number of characters and the resolution, so to use different font-sizes in the script depending on window resolution and the number of characters of the title.
This is what I have right now:
$(document).ready(function () {
$(".boxes.concierto h2.nombreartista span a").each(function () {
var numChars = $(this).text().length;
if ((numChars >= 1) && (numChars < 20)) {
$(this).css("font-size", "20px");
}
else if ((numChars >= 20) && (numChars < 30)) {
$(this).css("font-size", "18px");
$(this).css("line-height", "20px");
}
else if ((numChars >= 30) && (numChars < 60)) {
$(this).css("font-size", "15px");
$(this).css("line-height", "18px");
}
else if ((numChars >= 100) && (numChars < 140)) {
$(this).css("font-size", "0.9em");
}
else {
$(this).css("font-size", "0.8em");
}
});
});
I have tried to add:
if($(window).width() >= 1300){
// do your stuff
}
at the begining and end of my script but is not working.
Any idea how can I join this two functions correctly?
Thank you so much
you probably want to create a condition where either the number of characters or the resolution change the text size.
use the or-operator || in your if condition
if ( ((numChars >= 20) && (numChars < 30)) || $(window).width() >= 1300 ) {
$(this).css("font-size", "20px");
}
a better way
the conditions might get quite complex. a better way would be to setup a formula like:
var textSize = 1/numChars * $(window).width() * factor;
if you want the text size to change in steps you can do something like this:
var stepSize = 3;
var steppedTextSize = Math.floor(textSize/stepSize) * stepSize;
the steppedTextSize will have values in increments of 3. like: 12, 15, 18, ...