jquery if else doesnt give back an alert message - javascript

everything is writen in an external javascript file what I included in the html I also have the jquery link in there.
I tried to change put the if statment on diffrent positions in the code, I looked arround if the width was incorrect and some other things whitch are inrelevent at the moment.
When I changed the $foodcheck).width > '0px' to a < and the else if to a > the alert did work but ofc I only want it to pop up if the width = 0
I want it to give back the alert message.
var $foodcheck = $('#greenfood');
if(($foodcheck).width > '0px') {
document.getElementById("f").onclick = function(){
var random = Math.random();
if(random > 0.0 && random <= 0.5) {
$("#greenfood").animate({width: "-=30px"});
} else if(random > 0.9) {
$("#greenfood").animate({width: "-=80px"});
} else {
$("#greenfood").animate({width: "140px"});
}
};
} else if(($foodcheck).width =< '0px'){
alert("Works");
}

You have quite a few problems with your code.
First of all, ">" and "<" should be done with numbers. Therefore the code >"0px" makes NO sense in this context, as you are really comparing the dictionary order of the characters in ASCII. Not the value of the integers.
i.e.
"a" < "b" //true as 'a' < 'b' => 97 > 98 (converted to ASCII numbers)
"ab" < "ac" // true as 'a' == 'a' and 'b' < 'c'
"ab" < "ac" // true as 'a' == 'a' and 'b' < 'c'
"5px" > "11px" //true as '5' > '1'
What you should have done is compared the value like so:
5 > 11 //false as 5 < 11
Here is your corrected code:
var $foodcheck = $('#greenfood');
if($foodcheck.width() > 0) { // CHANGE: Additional Brackets were not needed. width should be width()
$("#f").click(function() { //This is the jquery way of doing events although your way also works
var random = Math.random();
if (random > 0.0 && random <= 0.5) {
$foodcheck.animate({width: "-=30px"}); //IMPROVEMENT: used stored variable instead of finding the object again.
} else if(random > 0.9) {
$foodcheck.animate({width: "-=80px"});
} else {
$foodcheck.animate({width: "140px"});
}
});
} else if ($foodcheck.width() =< 0){
alert("Works");
}

jQuery's width() returns the computed width in pixels so you need to update you script to call it correctly. (note, its a function so needs the parenthesis).
Here's a working example:
$(function(){
var $foodcheck = $('#greenfood');
if($foodcheck.width() > 0) {
document.getElementById("f").onclick = function(){
var random = Math.random();
if(random > 0.0 && random <= 0.5) {
$foodcheck.animate({width: "-=30px"});
} else if(random > 0.9) {
$foodcheck.animate({width: "-=80px"});
} else {
$foodcheck.animate({width: "140px"});
}
}
} else {
alert("$foodcheck is <= 0 or undefined");
}
});
#greenfood {background:green; width:200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="greenfood">greenfood</div>
<button id="f">click</button>
UPDATE:
From your comments it's apparent that you want to check the width every time. Simply move the width checking clause inside the onclick event:
$(function(){
var $foodcheck = $('#greenfood');
document.getElementById("f").onclick = function(){
var random = Math.random();
if($foodcheck.width() > 0) {
if(random > 0.0 && random <= 0.5) {
$foodcheck.animate({width: "-=30px"});
} else if(random > 0.9) {
$foodcheck.animate({width: "-=80px"});
} else {
$foodcheck.animate({width: "140px"});
}
} else {
alert("$foodcheck is <= 0");
}
}
});
#greenfood {background:green; width:200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="greenfood">greenfood</div>
<button id="f">click</button>

I think you're doing it wrong at this line:
($foodcheck).width > '0px')
It should be
($foodcheck).width > 0)
And this line:
else if(($foodcheck).width =< '0px')
Should be:
else if(($foodcheck).width =< 0)

else if(($foodcheck).width =< '0px'){
this code throw error "<=" not "=<" if everything with the html is ok and you have element with id="f" this will fix it !
also $foodcheck).width must be $foodcheck).width() <= 0 number not string like your example

Related

Javascript Element.ClassName always returning true on mousewheel change

I have a scroll wheel function that changes the class of a div as you scroll down or up.
It is actually functioning really well in all modern browsers, the thing is, it is trying to change the class everytime it is executing, even though I have a validation that should stop this from happening.
The function asks that if the div already has that class active then it should not change, but if you look at the console it is trying to do it every time despite that validation.
I don't know why the className method always returns true.
I used jquery's hasClass function and had the same behavior.
Thank you so much for your help.
JAVASCRIPT CODE:
var sections = ['one', 'two', 'three', 'four', 'five'];
function changeSection(section) {
for (var x = 0; x < sections.length; x++) {
$('#bg-main').removeClass('bg-' + sections[x]);
if (sections[x] === section) {
if (document.getElementById('bg-main').className != ('bg-' + section)) {
$('#bg-main').addClass('bg-' + section);
console.log("Active: " + section);
} else {
console.log("Inactive: " + sections[x]);
}
}
}
}
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel"
if (document.attachEvent)
document.attachEvent("on" + mousewheelevt, displaywheel)
else if (document.addEventListener)
document.addEventListener(mousewheelevt, displaywheel, false)
var position = 0;
function displaywheel(e) {
var evt = window.event || e
var delta = evt.detail ? evt.detail : evt.wheelDelta
if (delta < 0) {
position = (mousewheelevt == 'DOMMouseScroll') ? position - 1 : position + 1;
} else {
position = (mousewheelevt == 'DOMMouseScroll') ? position + 1 : position - 1;
}
if (position < 0) position = 0;
if (position > 100) position = 100;
// Change sections on Scroll
if (position >= 0 && position <= 19) {
changeSection('one');
} else if (position >= 20 && position <= 39) {
changeSection('two');
} else if (position >= 40 && position <= 59) {
changeSection('three');
}
if (position >= 60 && position <= 79) {
changeSection('four');
} else if (position >= 80 && position <= 100) {
changeSection('five');
}
}
CSS CODE:
#bg-main {
width: 100%;
height: 300px;
}
.bg-one {
background-color: blue;
}
.bg-two {
background-color: red;
}
.bg-three {
background-color: green;
}
.bg-four {
background-color: yellow;
}
.bg-five {
background-color: purple;
}
HTML CODE:
<div id="bg-main" class="bg-one">SCROLL TO SEE THE CHANGE OF BACKGROUND</div>
Working fidddle:
https://jsfiddle.net/9vpuj582/
You are removing the class before you check to see if the element has the class that you passed into your function (so your if statement will never evaluate as false).
The placement of the following line of code in your changeSection function is your issue:
$('#bg-main').removeClass('bg-'+sections[x]);
You could simplify your current function quite a bit. First check if the element already has the class you want. Then, if not, remove all classes from the element (rather than looping through them and checking each one) and then add the new class. For example:
const bg = $('#bg-main');
function changeSection(section) {
if (!bg.hasClass('bg-' + section)) {
bg.removeClass();
bg.addClass('bg-' + section);
}
}

What am I missing? Set font color javascript

function f2color1(Fahr) {
var Fahr;
if (Fahr >= 80) {
console.log(Fahr.fontcolor("red"));
} else if (Fahr <= 40) {
console.log(Fahr.fontcolor("blue"));
}
}
f2color1(30);
This is what I've written so far. I get the following error:
Uncaught TypeError: Cannot set property 'color' of undefined
at f2color2 (script.js:34)
at script.js:38
You were probably going for this, assuming that Fahr is a number.
function f2color1(Fahr) {
if (Fahr >= 80) {
console.log('%c' + Fahr, 'color: red');
} else if (Fahr <= 40) {
console.log('%c' + Fahr, 'color: blue');
}
}
f2color1(30);
Fahr is already defined as a parameter, so var Fahr is unnecessary.
Fahr is a variable you created which you are using as an integer, integers do not have an attribute called fontColor, so you will need to recreate the function with a string or change Fahr to a string so you can change font color
Somethig like this code work, I have used Fahr as a integer for the if statement and then converted it to a string:
function f2color1(Fahr) {
if (Fahr >= 80) {
console.log(String(Fahr).fontcolor("red"));
} else if (Fahr <= 40) {
console.log(String(Fahr).fontcolor("blue"));
}
}
f2color1(30);

If/Else validation not working like it should

I am trying to get this validation to work and I am having some difficulties. This is the code that I have:
function validateCarsMinMax(v) {
if (tfRateLoc1.getValue() > '0' && tfRateLoc2.getValue() > '0') {
if (tfRateLoc3.getValue() != '0') {
return '1B cannot contain a value if CW is entered';
}
} else return true
}
It seems to not like the && tfRateLoc2.getValue() > '0' line because it works just fine when I take it out. Any suggestions?
I am assuming that getValue() returns a number and '0' is a string not a number so the comparison incorrect.
if (tfRateLoc1.getValue() > 0 && tfRateLoc2.getValue() > 0) {
if (tfRateLoc3.getValue() != 0) {
Other issue is you never return a value if if (tfRateLoc3.getValue() != '0') { is false
This worked for me:
function validateCarsMinMax(v){
if (tfRateLoc1.getValue() > 0 || tfRateLoc2.getValue() > 0){
if (tfRateLoc3.getValue() > 0){
return '1B cannot contain a value if CW is entered';
}
} else return true
}
if (parseInt(tfRateLoc1.getValue()) > 0 && parseInt(tfRateLoc2.getValue()) > 0
&& parseInt(tfRateLoc3.getValue()) != 0)
{
return '1B cannot contain a value if CW is entered';
}else return true

Change DIV Background Color, Depending on Its Width

I'm wanting to use jQuery to dynamically modify the background color of a <div>, based on its CSS property, width value.
The usage is for some form of color-coded meter, which indicates how well (or poorly) a device performs in a specific category (there are 5), and then there is one 'overall' category, which produces the overall score, based on a little math (add all 5 together and divide the answer by 5).
I have tried two methods, one based on the little jQuery knowledge I have, and the other adapted from an answer on SO. Both are included in the JSFiddle I have provided, with the latter commented out.
Here are the colors and the ranges of the widths for each:
0-24% = red - #a41818
25-49% = orange - #87581c
50-74% = yellow - #997815
75-90% = yellowgreen - #7ba01c
91-100% = green - #3a8d24
Thanks!
I'd suggest:
$('.rating-bar').css('background-color', function(){
var percentage = parseInt($(this).data('size'), 10);
if (percentage > 0 && percentage < 25){
return '#a41818'
}
else if (percentage > 24 && percentage < 50) {
return '#87581c';
}
else if (percentage > 49 && percentage < 75) {
return '#997815';
}
else if (percentage > 74 && percentage < 90) {
return '#7ba01c';
}
else if (percentage > 89 && percentage <= 100) {
return '#3a8d24';
}
});
JS Fiddle demo.
There were a few semantic problems ($(e) used instead of $(this), ($(document).ready nested strangely), and the logic you've used requires the ratio of each bar's width to the parent bar, not the width itself.
Try this: http://jsfiddle.net/VFSUN/1/
$(document).ready(function () {
var bar = $('.rating-bar');
bar.css("background-color", "#7ba01c");
var parentWidth = parseInt($('.rating-bar-bg').css("width"));
$('.rating-bar').each(function () {
var e = $(this).css("width");
e = parseInt(e);
ratio = e / parentWidth * 100;
if (ratio <= 24) {
$(this).css("background-color", "#a41818");
} else if (ratio >= 25 && e < 50) {
$(this).css("background-color", "#87581c");
} else if (ratio >= 50 && e < 75) {
$(this).css("background-color", "#997815");
} else if (e >= 75 && e < 91) {
$(this).css("background-color", "#7ba01c");
} else if (ratio >= 91) {
$(this).css("background-color", "#3a8d24");
}
});
});
I suggest you are starting at wrong point by checking width, when in fact you need to be setting width based on the data-size attribute. This size can then be used to set bckground color
$(document).ready(function() {
$('.rating-bar').each(function(){
var $bar=$(this), size=$bar.data('size');
$bar.width(size+'%').css("background-color", getBackground( size))
});
});
function getBackground( e){
var color= "#a41818";/* < 24*/
if (e >= 25 && e < 50) {
color= "#87581c";
} else if (e >= 50 && e < 75) {
color= "#997815";
} else if (e >= 75 && e < 91) {
color= "#7ba01c";
} else if (e >= 91) {
color= "#3a8d24";
}
return color
}
DEMO

Javascript Testing Corners of an Array (Grid)

I'm doing this project trying to reproduce Schelling's Segregation model. I have a function(below) that is testing to see if the four immediate adjacent cells of the array are either the same or different or empty compared to the current cell being tested.
There are four possible spots to be tested for every cell in the array. But on corners and side spots, obviously you cant test spaces that are out of bounds. So in the function, if it finds one of the out of bounds spaces it decrements the number total around the cell. However, it keeps crashing telling me that I have an Uncaught Reference Error: Cannot read property '0' of undefined. I can't tell why its crashing.
The final lines of this code take the number of goods(similar cells) and the total number of cells around it (empty cells do not count) and gets a percentage similar.
Any help would be appreciated into telling me why it might be crashing and giving me an error? Thanks!
model.Test = function( i, j )
{
var numberToTest= 4;
var goods= 0;
if ((i - 1) >= 0)
{
if (model.BoardArray[i-1][j] != "E")
{
if (model.BoardArray[i][j] == model.BoardArray[i-1][j])
{
goods++;
}
}
else
{
numberToTest--;
}
}
else
{
numberToTest--;
}
if((i + 1) < $("#BoardSizeValue").val())
{
if (model.BoardArray[i+1][j] != "E")
{
if (model.BoardArray[i][j] == model.BoardArray[i+1][j])
{
goods++;
}
}
else
{
numberToTest--;
}
}
else
{
numberToTest--;
}
if ((j - 1) >= 0)
{
if (model.BoardArray[i][j-1] != "E")
{
if (model.BoardArray[i][j] == model.BoardArray[i][j-1])
{
goods++;
}
}
else
{
numberToTest--;
}
}
else
{
numberToTest--;
}
if ((j + 1) < $("#BoardSizeValue").val())
{
if (model.BoardArray[i][j+1] != "E")
{
if (model.BoardArray[i][j] == model.BoardArray[i][j+1])
{
goods++;
}
}
else
{
numberToTest--;
}
}
else
{
numberToTest--;
}
var similar = $("#SimilarSlider").val()/100;
if (numberToTest == 0)
{
return false;
}
else
{
var needed = goods/numberToTest;
if (needed >= similar)
{
return false;
}
else
{
return true;
}
}
}
From looking at your code, you would only get a Reference Error: Cannot read property '0' of undefined. if i was out of the bounds of the array.
I think the problem might be in this part of the code:
if ((i - 1) >= 0) {
if (model.BoardArray[i-1][j] != "E") {
if (model.BoardArray[i][j] == model.BoardArray[i-1][j]) {
if i = $("#BoardSizeValue").val() and $("#BoardSizeValue").val() is a one-based index of the array size, then [i-1] would be okay, but not [i]. So try adjusting your code to this:
if ((i - 1) >= 0 && i < $("#BoardSizeValue").val()) {
if (model.BoardArray[i-1][j] != "E") {
if (model.BoardArray[i][j] == model.BoardArray[i-1][j]) {
This would also apply to the j comparisons as well.

Categories