I'm trying to make a button with two functions:
function bigfont()
{var font_is_small = true
if (font_is_small = true)
{document.getElementById('one').className=
document.getElementById('one').className.replace("font1","font2");
document.getElementById('two').className=
document.getElementById('two').className.replace("font1","font2");
document.getElementById('three').className=
document.getElementById('three').className.replace("font1","font2");
document.getElementById('four').className=
document.getElementById('four').className.replace("font3","font4");
font_is_small = true;}
if(font_is_small = false)
{document.getElementById('one').className=
document.getElementById('one').className.replace("font2","font1");
document.getElementById('two').className=
document.getElementById('two').className.replace("font2","font1");
document.getElementById('three').className=
document.getElementById('three').className.replace("font2","font1");
document.getElementById('four').className=
document.getElementById('four').className.replace("font4","font3");
font_is_small = true;}}
But the variable doesn't change. Could anybody help me?
To change a boolean to its opposite value you can use negation (!), for example x = !x means "set x to false if it's truthy or to true if it's falsy".
If you want the function to toggle between small and big font the simplest way is to place te variable outside of the function:
http://jsfiddle.net/zvoeLu9p/
var font_is_small = true;
function bigfont()
{
font_is_small = !font_is_small; // switch the boolean
if (font_is_small){ // no need for == true
document.body.className=
document.body.className.replace("font1","font2");
}
else { // no need for if condition
document.body.className=
document.body.className.replace("font2","font1");
}
}
But you have the variable font_is_small in true all the time you have to change it to false in your code you don't do this.
It's where your variable is created and assigned, your equivalence in the if (= means assign) and you are setting it to true in BOTH if statements. ... try ...
var font_is_small = true;
Based on your usage, font_is_small should be a global, not passed in or created inside the function.
function bigfont() {
if (font_is_small === true) {
document.getElementById('one').className="font2":
document.getElementById('two').className="font2":
document.getElementById('three').className="font2":
document.getElementById('four').className="font2":
font_is_small = false;
}
if(font_is_small === false) {
document.getElementById('one').className="font1":
document.getElementById('two').className="font1":
document.getElementById('three').className="font1":
document.getElementById('four').className="font1":
font_is_small = true;
}
}
Also, the replace wasn't doing anything significant ... I figured out the two line formatting after fixing this ... this assignment is simpler and clearer.
Related
I am having some trouble with this current lesson on control flow with JavaScript...
The question states:
In this exercise, you will be given a variable, it will be called value.
You will also be given another variable, it will be called greaterThanFive.
Using an 'if statement' check to see if the value is greater than 5. If it is, re-assign the boolean true.
code with stars next to it is the code I was given.
**let greaterThan5 = false;**
if (value > 5 ) {
console.log("That is true");
}
**return greaterThanFive;**
I have tried a number of different ways on how to write the correct code but it obviously is not right.
I tried assigning var value = 10;and then finishing the code as above but it says value has already been assigned. I have tried changing the boolean to let greaterThanFive = true;
The hint only tells me that "should return boolean value equal to 10" and "expected true to be false"
Please help, I have been working on this simple code it may seem for a week and do not want to move on to the next lesson without fully understanding this question.
Thank You!
You have two different variables; greaterThan5 and greaterThanFive.You also have a return statement, which will only work inside of a function.
I believe what you're looking for is something like the following, which passes a value into the function, then checks whether the value is greater than five or not, setting the variable to true inside of the if conditional if it is. The function then returns the greaterThan5 variable's truthiness:
function greater(value) {
let greaterThan5 = false;
if (value > 5) {
greaterThan5 = true;
}
return greaterThan5;
}
console.log(greater(10));
console.log(greater(3));
Which can be further simplified to a simple one-line return statement:
function greater(value) {
return value > 5;
}
console.log(greater(10));
console.log(greater(3));
So, the first clue in the code is the return statement. That means you are likely being asked to write a function that, given some value, checks to see if that value is greater than 5.
Let's define it using your existing code:
function isGreaterThan5(value) {
let greaterThan5 = false;
if (value > 5 ) {
console.log("That is true");
}
return greaterThan5;
}
So right now, we're always going to return false. All you need to do is reassign the value of greaterThanFive if value > 5. So, you can simply do that in your if-statement:
function isGreaterThan5(value) {
let greaterThan5 = false;
if (value > 5 ) {
greaterThan5 = true;
}
return greaterThan5;
}
You can now test your code by calling the function with various values:
isGreaterThan5(1); // returns false
isGreaterThan5(5); // returns false
isGreaterThan5(6); // returns true
And we're done!
I'm wondering if what confused you was the use of let. You might want to read more about var, let, and const.
if (value > 5) {greaterThanFive = true;}
Am attempting to create a static navigation panel which becomes absolute at the bottom before the footer when reaching the end of the page content.
As I am developing for wordpress the page could be of varying height so I have attempted to trigger the absolute positioning when the nav panel “collides” with the footer.
So far I have used this code I found here
function collision($archive, $footer){
var archivexPos = $archive.offset().left;
var archiveyPos = $archive.offset().top;
var archiveHeight = $archive.outerHeight(true);
var archiveWidth = $archive.outerWidth(true);
var archiveb = archiveyPos + archiveHeight;
var archiver = archivexPos + archiveWidth;
var footerxPos = $footer.offset().left;
var footeryPos = $footer.offset().top;
var footerHeight = $footer.outerHeight(true);
var footerWidth = $footer.outerWidth(true);
var footerb = footeryPos + footerHeight;
var footerr = footerxPos + footerWidth;
if (archiveb < footeryPos || archiveyPos > footerb || archiver < footerxPos || archivexPos > footer) return Boolean = false;
return Boolean = true;
And used a global variable of Boolean to pass to this function
$(window).on('scroll', function() {
var scrollmath = Math.round($(window).scrollTop());
var archiveValue = scrollmath + 48;
var archiveBottom = archiveValue + 'px';
console.log('collision boolean', Boolean)
if (Boolean = false) {
$('#archive').css('position', 'fixed');
$('#archive').css('top', '48px');
} else {
$('#archive').css('position', 'absolute');
$('#archive').css('top', archiveBottom);
}
My problem is the if statement seems to be creating another Boolean variable? As when I comment it out I can see that the console reports the Boolean variable as expected. However when I leave it in and they collide this happens
Whats happened here?
The primary thing that's happening is that you're using = for comparison. JavaScript uses == (or ===), not =. = is always assignment.
But when testing the value of a boolean, you don't want == or != anyway, just use the boolean directly:
if (flag) {
// It was true
} else {
// It was false
}
Or if you're just testing for false:
if (!flag) {
// flag was false
}
(Note that because JavaScript does type coercion, that will also work with variables containing values other than booleans: Any truthy value coerces to true, any falsy value coerces to false. The falsy values are 0, "", NaN, null, undefined, and of course, false; all other values are truthy.)
Separately: Boolean is not a good choice for a variable name, as it's part of the JavaScript standard library (a function).
Also, your current collision function does two things:
It sets Boolean to true or false
It returns the value it set
In general, all other things being equal, it's best if a function doesn't have side-effects like that. If the caller wants to set Boolean to the return value of the function, he/she can, there's no need for the function to do it — it's already returning the value.
And finally: Global variables are, in general something to avoid. The global namespace on browsers is incredibly crowded and it's easy to get conflicts (for instance, a global called name may well not work as expected, because there's already a name global [it's the name of the window]).
no, your real Problem is, that you overwrite the constructor for the Boolean Type.
1st. stick to coding conventions: Only classes start with an uppercase-letter.
2nd. local vars have to be declared with the var-Keyword (or let for block-scoped vars, or const).
otherwise you reference a var from a surrounding scope; and in the end, the global scope.
3rd. the equal-sign:
=== means typesafe comprison
3 === 3 //=> true
3 === '3' //=>false
== means simple comparison
3 == '3' //=> also true now
= means assignment, not comparison
var foo = 3;
if it inside of some other code like
var bar = 42 + (foo = 3);
//it works basically like
var bar = 42 + (function(){
foo = 3;
return 3; //NOT FOO!!! not even foo after the assignment
})();
//the same way, that this:
var bar = 42 + foo++;
//works basically like this:
var bar = 42 + (function(){
var result = foo;
foo = foo+1;
return result;
})();
I am using jstree library to display a tree.
In the code below, I am looping through the selected nodes in the tree and based on some conditions, I am assigning a variable 'allow_edit' a boolean value.
I would like to break the main loop if 'allow_edit = false'.
I tried using label and breaking the loop but this does not seem to work. I am getting undefined label.
loop1:
$j.each($j("#demo2").jstree("get_selected"), function(index, element) {
var selected_node_depth = parseInt($j(element).attr('node_depth'));
var allow_edit = false;
var array_first_filter = $j.grep(array_first, function(v) { return v[1] != "not detected";})
var array_second_filter = $j.grep(array_first_filter, function(v) { return v[3] > selected_node_depth;})
if (array_second_filter.length === 0 || array_second_filter.length == null)
{
allow_edit = true;
}
else{
alert("Confliction exists in your selected terms.");
allow_edit = false;
//break loop1; /** not working, getting undefined label **/
}
}
Any suggestions on how to break the main loop if 'allow_edit = false'? Thanks a lot
If the function you pass to .each() returns false, the iteration will stop.
else {
allow_edit = false; // pointless since you're about to return ...
return false;
}
Also, as a programming style note, any construction of the form:
if (something) {
flag = true;
}
else {
flag = false;
}
can be better written as simply:
flag = something;
In JavaScript, to force flag to be boolean (true or false), you can do this:
flag = !!(something);
The two ! (logical "not") operators force the expression ("something") to be evaluated as a boolean by the same rules as are used when that expression is the test clause of an if statement.
var canAssignMultiple="true";
var canWithdrawMultiple="true";
function onCheckUncheck()
{
if($(':checkbox[name^="checkedRecords"]:checked').length>0)
{
$("input[name='checkedRecords']:checked").each(function()
{
debugger;
var canAssign = $(this).attr("canAssign").toLowerCase();
var canWithdraw = $(this).attr("canWithdraw").toLowerCase();
canAssignMultiple= canAssignMultiple && canAssign;
canWithdrawMultiple= canWithdrawMultiple && canWithdraw;
if (canAssignMultiple == "false")
$("#assaignbutton").attr("disabled", "disabled");
else
$("#assaignbutton").removeAttr("disabled");
if (canWithdrawMultiple == "false")
$("#withdrawbutton").attr("disabled", "disabled");
else
$("#withdrawbutton").removeAttr("disabled");
});
}
else
{
$("#assaignbutton").attr("disabled", "disabled");
$("#withdrawbutton").attr("disabled", "disabled");
}
}
The variable canAssignMultiple is becoming true when each() function is called the second time though its value has changed to false in the first iteration.It should retain its value evrytime the loop runs.How to do this?
boolean (false, true) values are different than strings ("false", "true")
try
var canAssignMultiple = true;
var canWithdrawMultiple = true;
function onCheckUncheck() {
if ($(':checkbox[name^="checkedRecords"]:checked').length > 0) {
$("input[name='checkedRecords']:checked").each(function() {
debugger;
var canAssign = $(this).attr("canAssign").toLowerCase() == "true"; // make this a boolean expression
var canWithdraw = $(this).attr("canWithdraw").toLowerCase() == "true"; // make this a boolean expression
canAssignMultiple = canAssignMultiple && canAssign;
canWithdrawMultiple = canWithdrawMultiple && canWithdraw;
if (canAssignMultiple === false) $("#assaignbutton").attr("disabled", "disabled"); // use false (instead of "false")
else $("#assaignbutton").removeAttr("disabled");
if (canWithdrawMultiple === false) $("#withdrawbutton").attr("disabled", "disabled"); // use false (instead of "false")
else $("#withdrawbutton").removeAttr("disabled");
});
}
else {
$("#assaignbutton").attr("disabled", "disabled");
$("#withdrawbutton").attr("disabled", "disabled");
}
}
left comments where changes were made
As others have noted, the strings "true" and "false" do not function the same as the boolean values true and false. If you try to use a string in an if statement or with a logical operator such as &&, the string is converted to a boolean; and all non-empty strings are converted to true (i.e. they are "truthy"). That means the string "false" will work the opposite of how you expect, e.g. in ("false" && x) or in if ("false") {...}.
One way to fix your code is to change this line
canAssignMultiple = canAssignMultiple && canAssign;
to convert canAssign to a boolean in an explicit and correct way:
canAssignMultiple = canAssignMultiple && (canAssign == "true");
Then the && operator will work correctly, and canAssignMultiple will hold an actual boolean value.
And (as #mdmullinax noted, but I would do it differently) once canAssignMultiple is actually a boolean, you can change your if statements to treat them as such:
if (canAssignMultiple == "false")
should become
if (!canAssignMultiple)
And similarly with the corresponding withdraw stuff.
Does your HTML look like this?
<input canAssign="false" ...>
<input canAssign="true" ...>
If so, and you can't change the HTML, I suggest changing this:
canAssign = $(this).attr("canAssign").toLowerCase()
to this (to work with booleans from then on):
canAssign = $(this).attr("canAssign") == "true"
and this:
if(canAssignMultiple == "false")
to this (since it is a real boolean now):
if(canAssignMultiple)
If you can change HTML, I suggest you do it the HTML5-compliant way. First, all of your made up attributes should be prefixed data-. You can also change camelCase to hyphen-case. JQuery, when loading your data-attributes, will then perform the conversion from string if possible:
<input data-can-assign="false" ...>
<input data-can-assign="true" ...>
then jQuery will give you the boolean you want from this call:
canAssign = $(this).data("canAssign")
Of course, the same fix should be applied to all other string pseudo-booleans (that don't quite work with the boolean operators) as well.
The reason is: "false" is not exactly false. "false" && x will evaluate to x (not to "false" as you expect). On the other hand, false && x will evaluate to false.
I have a live -on click- event for a Header which has an arrow flipping up/down upon opening & closing it's contents.
The strangest thing is happening with ! followed by a variable -- which is supposed to flip it from true -> false, and vice versa. Basically it's not working at all, and it flips to false and stays there... Check out the fiddle to see what I mean.
I've deleted lots of code for the sake of brevity.
Demo Code
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).attr('data-state');
if (_state === 'true') {
// do stuff
}
else {
// do stuff
}
// This is where the issue is happening, it isn't flipping the Boolean value
// !"true" = false, !true = false, it works with strings or booleans
$(this).attr('data-state', !_state);
});
I can get it working perfectly fine if I do the following:
if (_state === 'true') {
// Manually flip the data-state boolean
$(this).attr('data-state', false);
}
Is there something I'm missing why this isn't working the way it should ?? Just wondering why it's doing this!
I think you are trying to do this:
http://jsfiddle.net/JKUJb/2/
if so, the problem was that you are using .attr() which returns a string, so if you convert:
!"true" //false
!"false" //false
.data() on the other hand returns the value already "casted
EDIT:
Just to be more clear, in javascript the only falsy values are:
false;
null;
undefined;
'';
0;
NaN;
So if you really wanted to use .attr(), you could, but I recommend that first you do:
var _state = $(this).attr('data-state') === 'true'; //if 'true' then true, false otherwise
Good luck!
Change your second line to:
var _state = $(this).attr('data-state') == 'true';
And in the if statement check for boolean:
if ( _state ) {
// do stuff
...
_state is a String (typeof _state === String //true) you need to convert it to a boolean first
(a String will alwase be true)
If you really want to use data- attributes for this, use jQuery's .data method to retrieve and set the value. It will automatically convert the string "true" into a Boolean, or the string "1" into a number:
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).data('state');
if (_state) {
// do something
}
$(this).data('state', !_state);
});
http://jsfiddle.net/mblase75/JKUJb/6/
Or you could toggle a class -- you can use the .hasClass method to return a Boolean:
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).hasClass('data-state');
if (_state) {
// do something
}
$(this).toggleClass('data-state');
});
http://jsfiddle.net/mblase75/JKUJb/3/