Jquery Cookies Issue - javascript

I'm trying to use jquery cookies to store the state of a tree menu between page loads, for some reason the below code does not seem to create a cookie inside the switch statement. Using the cookie code outside of the switch statement works fine. I'm not too great with JS so it could be a simple issue with my switch,
intImage = 2;
var catCookie = jQuery.cookie('catCookie');
if(catCookie == 'left')
{
intImage = 1;
};
if(catCookie == 'down')
{
intImage = 2;
};
function swapImage() {
switch (intImage) {
case 1:
intImage = 2
document.getElementById(".giftarrow").src = "http://www.domain.com/left-arrow.png";
jQuery.cookie('catCookie', 'left')
return(false);
case 2:
intImage = 1
document.getElementById(".giftarrow").src = "http://www.domain.com/down-arrow.png";
jQuery.cookie('catCookie', 'down')
return(false);
}
}
any help is greatly appreciated.

You seem to be missing some semicolons:
switch (intImage) {
case 1:
intImage = 2;
$('.giftarrow').attr('src', 'http://www.gracecole.co.uk/shop/skin/frontend/default/default/images/left-arrow.png');
jQuery.cookie('catCookie', 'left');
return(false);
case 2:
intImage = 1;
$('.giftarrow').attr('src','http://www.gracecole.co.uk/shop/skin/frontend/default/default/images/down-arrow.png');
jQuery.cookie('catCookie', 'down');
return(false);
}

Related

Executing multiple javascript files based on boolean conditions

I have around 5 javascript files in my WordPress website, And I tried to execute them one by one based on a boolean condition.
The javascript calls tag1.js if the count is 0.
tag2.js if the count is 1 and so on.
If the count reaches 4, the count resets to 0. And thus this is repeated continously. I tried this code. But it doesn't work even for the first time.
jQuery(document).ready(function( $ ) {
var canClick = true;
var count= 0;
$("body").click(function () {
if (canClick) {
if(parseInt(count) === 0) {
$.getScript("https:example.com/custom_js/atag1.js");
}
else if(parseInt(count) === 1) {
$.getScript("https:example.com/custom_js/atag2.js");
}
else if(parseInt(count) === 2) {
$.getScript("https:example.com/custom_js/atag3.js");
}
else if(parseInt(count) === 3) {
$.getScript("https:example.com/custom_js/atag4.js");
}
else if(parseInt(count) === 4){
$.getScript("https:example.com/custom_js/atag5.js");
count=0;
}
canClick = false;
setTimeout(() => {
canClick = true
},10000);
count = parseInt(count)+1;
}
});
});
Basically this code executes each javascript if the user clicks on the page with timeout differentiating the clicks.
If you want to load the script as per the number of clicks. Then you can look at this solution which will look more precise.
var clicks = 0;
document.addEventListener('click', () => {
loadJS();
++clicks;
});
function loadJS() {
if (clicks === 4) {
clicks = 0;
}
switch (clicks) {
case 0:
console.log('load first js');
break;
case 1:
console.log('load second js');
break;
case 2:
console.log('load 3rd js');
break;
case 3:
console.log('load 4th js');
break;
case 4:
console.log('load 5th js');
break;
default:
// code block
}
}
working demo

Javascript not working as I want to

Alright, I have made some JavaScript for an assessment. Everything worked fine until I put in a new function with a switch statement called:
function differentComments(answer) {
The program doesn't seem to load the follow function anymore when the function differentComments is in there:
function genQuestion() {
All of my JavaScript code is below (HTML is available on Pastebin):
var x, y; //the global variables
function aNumber() {
return Math.floor(1 + Math.random() * 12);
}
function genQuestion() {
x = aNumber();
y = aNumber();
dout = document.getElementById('Question');
dout.value = x + " times " + y;
}
function buttonPressed() {
var input = document.getElementById('Typed').value;
var answer = x * y;
if (input == answer) {
differentComments("Right");
genQuestion();
} else {
differentComments("Wrong");
}
document.getElementById('Typed').value="";
}
function differentComments(answer) {
var random_number = Math.floor(1 + Math.random() * 4);
if (answer == "Right") {
switch (random_number) {
case 1:
window.alert("Very Good!");
break;
case 2:
window.alert("Excellent!");
break;
case 3:
window.alert("Correct - Nice work!");
break;
case 4:
window.alert("Correct - keep up the good work!");
break;
default:
break;
}
} else (answer == "Wrong") {
switch (random_number) {
case 1:
window.alert("No. Please try again.");
break;
case 2:
window.alert("Wrong. Try once more.");
break;
case 3:
window.alert("Incorrect – Don’t give up.");
break;
case 4:
window.alert("No – keep trying.");
break;
default:
break;
}
}
}
Your else clause is incorrect.
if (answer == "Right") {
switch(random_number) {
...
}
else (answer == "Wrong") {
}
won't parse because the second test is missing an if.
if (answer == "Right") {
switch(random_number) {
...
}
else **if** (answer == "Wrong") {
}
Essentially you're treating an if() as if it's a switch(), and that's not syntactically correct.
The first thing you should do when you run into situations like this is use either jshint or jslint to check the syntactical correctness of your code.
In your code block :
if (answer == "Right") {
switch(random_number) {
...
}
else (answer == "Wrong") {
switch(random_number) {
...
}
}
mean you put if and else statement and a else condition only execute when all if conditions are return false. So there is no need to put conditional-statement(like in your case -else (answer == "Wrong") {) ).
You can simply write this :
if (answer == "Right") {
switch(random_number) {
...
}
else {
switch(random_number) {
...
}
}
It's means if your answer is not equal to Right, it always go to else statement.
OR
If you want to check for more conditions, use else if(){} statements.
if (answer == "Right") {
switch(random_number) {
...
}
else if (answer == "Wrong") {
switch(random_number) {
...
}
}
Read this

Boundary for canvas game in Javascript

I have to make a game for school with html5 canvas Javascript.
I am new to javascript and still learning but i really need some help with this issue that i have and would appreciate it if someone could help me out. I tried several things but nothing seems to work and im at a loss.
So this is the code for the player object. It can move from left to right.
Now the problem is that it leaves the canvas. I want it to stay in the canvas on the x axes.
// Things to do when keys are down
function onKeyDown(event) {
// prevent arrow keys from scrolling the page
if (event.keyCode >= 37 && event.keyCode <= 39) event.preventDefault();
switch (event.keyCode) {
case 37:
player.vx = -1;
player.image = player.imgLeft;
break; // left key
// case 38: player.vy = -1; break; // up key
case 39:
player.vx = 1;
player.image = player.imgRight;
break; // right key
}
}
// Things to do when keys are up
function onKeyUp(event) {
switch (event.keyCode) {
case 37:
case 39:
player.vx = 0;
player.image = player.original;
break; // left or right key released
// case 38: player.vy = 0; break; // up or down key released
}
}
This is what i got so far....
if ((player.x >= 800) && (player.x <= 0)) {
} else {
}
You could consider adding two functions to check that you're within bounds.
(Essentially the same as your code, albeit with my true condition returned in what would be your else statement.)
// returns true if param is in range [0..799]
function isInXrange(intPos)
{
if ((intPos>=0) && (intPos<800))
return true;
else
return false;
}
// returns true if param is in range [0..599]
function isInYrange(intPos)
{
if ((intPos>=0) && (intPos<600))
return true;
else
return false;
}
You could then add a function to move the player and another to handle colliding with the walls/wandering out of bounds
function movePlayer()
{
if (isInXRange(player.x))
player.x += player.vx;
if (isInXRange(player.y))
player.y += player.vy;
}
function handleOutOfBounds()
{
if (isInXRange(player.x) == false)
{
// do something;
}
if (isInYRange(player.y) == false)
{
// do something else
}
}
Basically just test to see if x + width (optional: + velocity) > canvas.width and the same for height.

Loop program again after method is executed

i guess this is a really simple problem, but i just can't get it to work! I want that my menu should show up again after that i have run a method. Thanks in advance.
function menu () {
var choice = prompt("0. Exit \n\n1. Fahrenheit to Celsius \n2. Celsius to Fahrenheit \n3. Guess a number");
choice = parseInt(choice);
if (choice > 4 || choice < 0) {
alert("FEL!!");
} else if (isNaN(choice)) {
alert("Måste vara en siffra");
}
switch (choice) {
case 0:
choice = false;
break;
case 1:
CelsiusToFarenheit();
break;
case 2:
FahrenheitToCelsius();
break;
case 3:
Guess();
break;
}
return choice;
}
do {
menu();
} while(choice == true);
you forgot to store the variable returned by the menu() function :
function menu () {
var choice = prompt("0. Exit \n\n1. Fahrenheit to Celsius \n2. Celsius to Fahrenheit \n3. Guess a number");
choice = parseInt(choice);
if (choice > 4 || choice < 0) {
alert("FEL!!");
} else if (isNaN(choice)) {
alert("Måste vara en siffra");
}
switch (choice) {
case 0:
choice = false;
break;
case 1:
CelsiusToFarenheit();
break;
case 2:
FahrenheitToCelsius();
break;
case 3:
Guess();
break;
}
return choice;
}
var choice;
do {
choice = menu();
} while(choice == true);
You are calling Menu() and after it executes, it is done. Therefore you need to run Menu() again.

jQuery: part of a function not executing

I have a tabbed setup on the page and I want to automatically make corresponding menu tab highlighted as well as corresponding content div show depending on # hash.
Example:
http://design.vitalbmx.com/user_menu/member_profile_so.html -- no hash, opens 1st tab
http://design.vitalbmx.com/user_menu/member_profile_so.html#setup -- #setup, should open "Setup" tab
As you can see it works for highlighting "Setup" tab. But content div does not change.
The script is below:
var tab_content_current = 1;
switch (window.location.hash) {
case '#activity': tab_content_current = 1; break;
case '#friends': tab_content_current = 2; break;
case '#photos': tab_content_current = 3; break;
case '#videos': tab_content_current = 4; break;
case '#setup': tab_content_current = 5; break;
case '#forum': tab_content_current = 6; break;
case '#blog': tab_content_current = 7; break;
case '#comments': tab_content_current = 8; break;
case '#favorites': tab_content_current = 9; break;
case '#profile-comments': tab_content_current = 10; break;
default: tab_content_current = 1;
}
if (tab_content_current != 1) {
change_active_tab (tab_content_current);
}
function tabs_toggle (id) {
if (id != tab_content_current) {
change_active_tab (id);
tab_content_current = id;
}
}
function change_active_tab (id) {
$j('.profile_tabs li').removeClass('active');
if (id < 8) $j('.profile_tab_'+id).addClass('active');
$j('.profile_content').hide();
$j('#profile_content_'+id).fadeIn();
}
Note that it works when you actually click menu tabs.
Any help to fix this problem would be greatly appreciated.
Move the script to the very bottom of the page, after the profile_content divs. That way they will be in the DOM before the scripts run. It is also best to put scripts at the bottom of the page for speed reasons.
That part of the code is not inside a jQuery ready() call, so the DOM is not yet loaded when it runs.
EDIT: The reason the tabs work, is that the script appears to be in the middle of the HTML content. The tas come before the script, and the content comes after. So that tabs are loaded, and the content sections are not.
Do this:
$(document).ready(function() {
var tab_content_current = 1;
switch (window.location.hash) {
case '#activity': tab_content_current = 1; break;
case '#friends': tab_content_current = 2; break;
case '#photos': tab_content_current = 3; break;
case '#videos': tab_content_current = 4; break;
case '#setup': tab_content_current = 5; break;
case '#forum': tab_content_current = 6; break;
case '#blog': tab_content_current = 7; break;
case '#comments': tab_content_current = 8; break;
case '#favorites': tab_content_current = 9; break;
case '#profile-comments': tab_content_current = 10; break;
default: tab_content_current = 1;
}
if (tab_content_current != 1) {
change_active_tab (tab_content_current);
}
function tabs_toggle (id) {
if (id != tab_content_current) {
change_active_tab (id);
tab_content_current = id;
}
}
function change_active_tab (id) {
$j('.profile_tabs li').removeClass('active');
if (id < 8) $j('.profile_tab_'+id).addClass('active');
$j('.profile_content').hide();
$j('#profile_content_'+id).fadeIn();
}
});
Or just place the script at the end of the page. Good idea to use ready() anyway, though.
Try setting your <li> elements up like this:
<ul class="profile_tabs light">
<li class="profile_tab_1 active">Activity</li>
you can more easily write some jQuery to tab like so:
var tab_content_current = 1;
function GetIndex($obj) { return $(this).parent().children().index($obj); }
$j(function(){
$j(".profile_tabs li").click(function(e){
e.preventDefault();
change_active_tab(GetIndex(this) + 1)
});
function change_active_tab (id) {
tab_content_current = id;
$j('.profile_tabs li').removeClass('active');
if (id < 8) $j('.profile_tab_'+id).addClass('active');
$j('.profile_content').hide();
$j('#profile_content_'+id).fadeIn();
}
var hash = window.location.hash;
if (hash != null && hash != "")
{
var $li = $(".profile_tabs li a[href=" + hash + "]");
change_active_tab(GetIndex($li) + 1)
}
});

Categories