How to change a javascript variable? - javascript

I'm trying to change a variable depending on what it's current value is:
window.addEventListener("popstate", function(e) {
if (direction === leftnav){
direction = rightnav
}
else{
direction = leftnav
};
loadPage(location.pathname);
});
this doesn't seem to work somehow :s
can someone help me with this?
Thanks in advance :)
EDIT: here is the full js file: http://pastebin.com/7zZseW74
EDIT 2: what seems to happen is that the loadPage function just does not seem to fire...

Try using == instead of ===:
if (direction == leftnav) {
direction = rightnav;
} else {
direction = leftnav;
}
Also, do include proper ; inside if and else clauses. You could also provide more information in order to get better help. Information like: what are leftnav and rightnav variables. If they are not variables but literals, you should enclose them within ". Like "rightnav" and "leftnav".

if (direction == leftnav){
^ requires only 2 '=' signs.
should be correct for the rest.

I believe all you're missing is semicolons.
if (direction == leftnav) {
direction = rightnav;
} else {
direction = leftnav;
}
Also, unnecessary ===

try this
if (direction == 'leftnav')
{direction = 'rightnav';}
else
{direction = 'leftnav';}

You haven't said a thing about leftnav and rightnav variable, so I suspect that you may want to use strings ('leftnav' and 'rightnav') instead, otherwise both are likely to be undefineds.
EDIT: Now that you posted the code, brief look at it suggests that yes, you wanted quoted strings.
window.addEventListener("popstate", function(e) {
direction = (direction=="leftnav")?"rightnav":"leftnav";
loadPage(location.pathname);
});

Related

simplify if else statement

I have some functionality dependent on many conditions. All variables in conditional statements are boolean variables and the code is the following and I don't like it:
if (userHasMoreThanOneMarket && isOnlyMarketSelected || !userHasMoreThanOneMarket && userHasMoreThanOneAgency) {
if (isOnlyAgencySelected) {
//do case 1
} else if (noAgencySelected && isOnlyMarketSelected) {
//do case 2
}
}
Is there a way to make it more understandable and nice?
That's about as concise as you're going to get with JavaScript. I suppose if you really wanted to, you could create variables to store your binary options:
var multiMarketOneSelected = userHasMoreThanOneMarket && isOnlyMarketSelected;
var singleMarketMultiAgency = !userHasMoreThanOneMarket && userHasMoreThanOneAgency;
if (multiMarketOneSelected || singleMarketMultiAgency) {
if (isOnlyAgencySelected) {
//do case 1
} else if (noAgencySelected && isOnlyMarketSelected) {
//do case 2
}
}
Though I don't really know if you gain much readability from that.
Your code seems fine, but if you don't like it you could do something like this (note that the only improvement here is style, if you like it better):
function check(){
return {
valid: userHasMoreThanOneMarket && isOnlyMarketSelected || !userHasMoreThanOneMarket && userHasMoreThanOneAgency,
case: [
isOnlyAgencySelected,
noAgencySelected && isOnlyMarketSelected
]
};
}
var conditions = check();
if (conditions.valid) {
if (conditions.case[0]) {
//do case 1
} else if (conditions.case[1]) {
//do case 2
}
}
Some things I would try to make the code more readable:
Initialise the variables in a way that you don't have to negate them again. So !userHasMoreThanOneMarket becomes userHasOneMarket
isOnlyMarketSelected sounds redundant to me. And you are checking it in the outer if-clause and the inner again.
You probably have a lot of code above this code snippet to initialise and set all this boolean values. Try return; statements after each variable to get rid of if-conditions.
I hope this helps.

Javascript: getElementById vs getElementsById (both works on different pages)

I'm struggling with a really weird problem...
I have two pages (quite the sames) where I need to disable some selects. On one of them (say page A), I use getElementById to retrieve my element, and on the second one (say page B) I use getElementsById (with a 's') to retrieve it (and it works on both cases).
What is weird is that if I use getElementsById on page A (with the 's'), it gives me the error "document.getElementsById is not a function", which is normal because this function (with the 's') normally doesn't exist. But I don't have this error on page B, and if I use getElementById (without the 's') on this page, it doesn't works !?!?
Can someone give me an explanation ? (I'll lose the few hairs left on my head if it continue ...)
Thanks in advance!
Ps: Sorry for my poor english!
Edit: Here is the code of my pages:
Page A:
function controleDelaiFranchise (casChoix){
var estAvecGarantie = <bean:write property="avecGarantie" name="simulationAutonomeForm" filter="false"/>;
if(estAvecGarantie ==true){
if(casChoix == 'Emprunteur'){
document.getElementById("assDelaiFranchiseEmpr").disabled = false;
}
else {
if(casChoix == 'CoEmprunteur'){
document.getElementById("assDelaiFranchiseCoEmpr").disabled = false;
}
}
}
else{
if(casChoix == 'Emprunteur'){
document.getElementsById("assDelaiFranchiseEmpr").disabled = true;
}
else {
if(casChoix == 'CoEmprunteur'){
document.getElementById("assDelaiFranchiseCoEmpr").disabled = true;
}
}
}
Page B:
function controleDelaiFranchise (casChoix){
var estAvecGarantie = document.getElementsByName("estAvecGarantie")[0].value;
if(estAvecGarantie){
if(casChoix == 'Emprunteur'){
document.getElementsById("assDelaiFranchiseEmpr").disabled = false;
}
else {
if(casChoix == 'CoEmprunteur'){
document.getElementsById("assDelaiFranchiseCoEmpr").disabled = false;
}
}
} else {
if(casChoix == 'Emprunteur'){
document.getElementsById("assDelaiFranchiseEmpr").disabled = true;
}
else {
if(casChoix == 'CoEmprunteur'){
document.getElementsById("assDelaiFranchiseCoEmpr").disabled = true;
}
}
}
}
Edit 2:
Ok so when it was not working on page B (without 's') I had
var estAvecGarantie = document.getElementsByName("estAvecGarantie")[0].value;
if(estAvecGarantie){ ... }
I replace it with
var estAvecGarantie = document.getElementsByName("estAvecGarantie")[0].value;
if(estAvecGarantie == true) { ... }
and now it works using getElementById without the 's'
But I still don't understand why it's still working with this damn 's' ... So my problem is solved (ish), but still, if someone have an explanation for why can I used getElementsbyId() even if the function doesn't exist (and specifically on one page only), I'm all ears because I hate when I don't understand ...
As described by James here id values have to be unique in a document, so there will be only one "element" that matches, rather than multiple "elements".
That is the reason, We should not use s while selecting elements. As Id can be selected only one at a time.
However, there are methods that return multiple elements which do use the plural "elements", such as getElementsByTagName.
Hope that clears your confusion
First things first:
Function-, or rather, methodnames in JavaScript are Case-Sensitive. This means that document.getElementById is not the same as document.getElementbyId.
The weird part:
document.getElementsById does not exsist in JavaScript, so it can't work by default. The only way this can work is if somebody created this function/method on the other page. A more obvious explanation is that you made a type-o on your second page. Maybe you forgot to write the S and you thought you didn't. Can you try again?

Combine if/else into one statement? (Javascript)

function changeButton () {
if (event.currentTarget.className == 'btnRed') {
event.currentTarget.className = 'btnGreen';
} else {
event.currentTarget.className = 'btnRed';
}
}
Let's say I have the above code. I have seen similar codes written that would combine these two, but I don't really remember how it did it. It was something like className = (btnGreen | btnRed).
I am very sorry for the vagueness of this question.
You can use the ternary operator (condition) ? (true) : (false)
event.currentTarget.className = event.currentTarget.className == 'btnRed' ? 'btnGreen' : 'btnRed';
I would go a little bit further, extract the strings into variables to remove the ability to mistype them across the solution. And refactor event.currentTarget into a variable.
var RED_BUTTON_CLASS = 'btnRed',
GREEN_BUTTON_CLASS = 'btnGreen';
var currentTarget = event.currentTarget;
currentTarget.className = currentTarget.className == RED_BUTTON_CLASS ? GREEN_BUTTON_CLASS : RED_BUTTON_CLASS;
This I feel will just make it easier in the long run, completely optional
Edit
So adding extra information from what Jan said.
var RED_BUTTON_CLASS = 'btnRed',
GREEN_BUTTON_CLASS = 'btnGreen';
These probably describe a state, so you could better name them:
var ERROR_BUTTON_CLASS = 'btnRed',
OK_BUTTON_CLASS = 'btnGreen';

If condition on windows load not working in javascript

The following code is not working and cant understand why. What am I doing wrong?
$(function() {
var advanced = localStorage['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true")|(advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
Check the OR operator. It should be like -
if((advanced == "true")||(advanced==true)){
This expression is not working:
if((advanced == "true")|(advanced==true)){
It’s enough to do:
if(advanced) {
because "true" as a string is also "truthy".
You are missing an extra |:
$(function() {
var advanced = localStorage.getItem['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true") || (advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
OR operator needs to be two |..Like this:
if((advanced == "true") || (advanced==true)){
If the variable advanced is a BOOLEAN, then you can simply use this:
if(advanced) {
// code here..
}
I think there is mistake in your javascript code.so you can not use "|" instead of "||"
so try by the following code gets solved your error.
$(function() {
var advanced = localStorage.getItem['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true")||(advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
As you say that a proper OR operator is still not working, then I suspect it must be a problem with the case.
Check this fiddle: http://jsfiddle.net/VTfQU/
Use this code to simplify your if condition:
var advanced = localStorage.getItem['advanced-search'];
advanced = advanced.toString().toLowerCase();
if (advanced == "true") {
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = "false";
}
The idea is to convert your data into lowercase and then just check the condition on that value. I have added toString() just to be safe, anyway getting a value out of local storage will always be a string.

cannot get a variable to pass from function called onclick

I am calling a function onclick secVar(sec1); which should run it through the script below, but it does not seem to be doing so, can someone tell me what I am doing incorrectly. I am new to javascript, and only have a little experience into scripting, and this code seems to be doing less and less of what I want it to.
<script type="text/javascript">
var sec1=0;
var sec2=0;
var sec3=0;
function secVar(){
if(sec1) {
sec1++;
document.getElementById('sec1text').innerHTML = sec1;
}
if(sec2) {
sec2++;
document.getElementById('sec2text').innerHTML = sec2;
}
if(sec3) {
sec3++;
document.getElementById('sec3text').innerHTML = sec3;
}
}
function largestVar(){
if (sec1 >= sec2 && sec1 >= sec3) {
//a
document.getElementById('rig').innerHTML = 'Test1';
} else if (sec2 >= sec1 && sec2 >= sec3) {
//b
document.getElementById('rig').innerHTML = 'Test2';
} else {
//c
document.getElementById('rig').innerHTML = 'Test3';
}
}
</script>
If this helps, The old code was the code below, before I tried to add in the script to determine the largest of the variables. It was incrementing the variables onclick, but no longer so. The onclick contained sec1Var() at that point.
<script type="text/javascript">
var sec1=0;
var sec2=0;
var sec3=0;
function sec1Var(){
sec1++;
document.getElementById('sec1text').innerHTML = sec1;
}
function sec2Var(){
sec2++;
document.getElementById('sec2text').innerHTML = sec2;
}
function sec3Var(){
sec3++;
document.getElementById('sec3text').innerHTML = sec3;
}</script>
If someone can explain to me what I am doing wrong I would greatly appreciate it.
I think it's hard to tell what your intention is. Sparticus has it right IF what you're trying to do is see if sec1, 2, and 3 are currently true or false (0 or 1). Since they are currently false, the code will never do anything as Sparticus correctly points out.
However, I'm not convinced that's actually what you MEAN to do. It looks like the condition you want to check is whether or not you're trying to increment sec1, 2, or 3. In other words, "If you are passing me sec1, increment it and update a piece of HTML".
But variables don't work that way. When you say secVar(sec1) what you are actually saying is `secVar(0)'. I don't think that's your intention.
So, a big waste of my time if I'm wrong, but because I'm already rolling along, let's pretend I'm right:
secVar needs to be able to accept a parameter, but right now you've declared it void. Changing it to accept a parameter is a first step:
function secVar(param) { ... };
But this still won't do anything. Because when you're still passing it "0" with your existing syntax. You need to pass it something that can be checked, like a string:
secVar('sec1');
When you do this, you can now update your conditions to check which string is being passed
if (param === 'sec1') { ... }
Here's a fiddle: http://jsfiddle.net/ch4yk/
Notes:
The fiddle includes jQuery just for easy brute-force event binding on the buttons. It's just an example. You don't need jQuery; bind your events however you want.
It is currently not doing anything with the largest value function, even though the code is in the fiddle
None of your counters will increment in this implementation.
When secVar() gets run, all the counters are at zero. They never increment because they start at zero.

Categories