How to simplify this 3 switch-case functions? - javascript

I want to simplify this long jquery/javascript code, can you help me? I still learn :)
Here's my jquery code:
$('.pagination-link').click(function() {
setTimeout(function() {
currentAnchor = $('body').attr('class');
switch (currentAnchor) {
case 'active-slide-1':
$('#rond').removeClass().addClass('rond1').animate();
break;
case 'active-slide-2':
$('#rond').removeClass().addClass('rond2').animate();
break;
case 'active-slide-3':
$('#rond').removeClass().addClass('rond3').animate();
break;
case 'active-slide-4':
$('#rond').removeClass().addClass('rond4').animate();
break;
case 'active-slide-5':
$('#rond').removeClass().addClass('rond5').animate();
break;
case 'active-slide-6':
$('#rond').removeClass().addClass('rond6').animate();
break;
case 'active-slide-7':
$('#rond').removeClass().addClass('rond7').animate();
break;
case 'active-slide-8':
$('#rond').removeClass().addClass('rond8').animate();
break;
default:
$('#rond').removeClass();
}
}, 50);
});
$('.overlay-menu > ul > li > a').click(function() {
setTimeout(function() {
currentAnchor = $('body').attr('class');
switch (currentAnchor) {
case 'active-slide-1':
$('#rond').removeClass().addClass('rond1').animate();
break;
case 'active-slide-2':
$('#rond').removeClass().addClass('rond2').animate();
break;
case 'active-slide-3':
$('#rond').removeClass().addClass('rond3').animate();
break;
case 'active-slide-4':
$('#rond').removeClass().addClass('rond4').animate();
break;
case 'active-slide-5':
$('#rond').removeClass().addClass('rond5').animate();
break;
case 'active-slide-6':
$('#rond').removeClass().addClass('rond6').animate();
break;
case 'active-slide-7':
$('#rond').removeClass().addClass('rond7').animate();
break;
case 'active-slide-8':
$('#rond').removeClass().addClass('rond8').animate();
break;
default:
$('#rond').removeClass();
}
}, 50);
});
$(window).mousewheel(function() {
setTimeout(function() {
currentAnchor = $('body').attr('class');
switch (currentAnchor) {
case 'active-slide-1':
$('#rond').removeClass().addClass('rond1').animate();
break;
case 'active-slide-2':
$('#rond').removeClass().addClass('rond2').animate();
break;
case 'active-slide-3':
$('#rond').removeClass().addClass('rond3').animate();
break;
case 'active-slide-4':
$('#rond').removeClass().addClass('rond4').animate();
break;
case 'active-slide-5':
$('#rond').removeClass().addClass('rond5').animate();
break;
case 'active-slide-6':
$('#rond').removeClass().addClass('rond6').animate();
break;
case 'active-slide-7':
$('#rond').removeClass().addClass('rond7').animate();
break;
case 'active-slide-8':
$('#rond').removeClass().addClass('rond8').animate();
break;
default:
$('#rond').removeClass();
}
}, 50);
});
I don't know if I have to use php to get the end of currentAnchor and put it as a parameters. Thank you for your help !
EDIT: I found that the default case is not necessary in my code. But I learn something new if I had my defaut case was important. So, here it's the new one:
function rondClass() {
setTimeout(function() {
currentAnchor = $('body').attr('class');
var currentClass = currentAnchor.replace('active-slide-', 'rond');
$('#rond').removeClass().addClass(currentClass).animate();
}, 50);
}
$('.pagination-link').click(rondClass);
$('.overlay-menu > ul > li > a').click(rondClass);
$(window).mousewheel(rondClass);
Thank you everyone !

You could just replace active-slide- with rond.
var currentAnchor = $('body').attr('class');
var newClass = currentAnchor.replace('active-slide-', 'rond');
$('#rond').removeClass().addClass(newClass).animate();
To handle the default case, you can handle this using indexOf or match:
// indexOf version
if (currentAnchor.indexOf('active-slide-') !== 0) {
$('#rond').removeClass();
} else {
$('#rond').removeClass().addClass(newClass).animate();
}
// match version
if (!currentAnchor.match(/^active-slide-/)) {
$('#rond').removeClass();
} else {
$('#rond').removeClass().addClass(newClass).animate();
}

Replace switch/case with programmatic approach and extract function to avoid code duplication.
var onClick = function() {
setTimeout(function() {
currentAnchor = $('body').attr('class');
var slide = currentAnchor.match(/active\-slide\-(\d)/);
if (slide) {
$('#rond').removeClass().addClass('rond' + slide[1]).animate();
} else {
$('#rond').removeClass();
}
}, 50)
})
$('.overlay-menu > ul > li > a').click(onClick);
$('.pagination-link').click(onClick);

Related

Javascript problem with switch statement that find not case: "none"

My code has to see if there is a ball in a mapPoint and then changing the color of the pixels where the ball is by the color of the ball.
Here is my code:
function UpdateColorInMapPoints(mapPointIndexs)
{
mapPointIndexs.forEach(mapPointIndex => {
var mapPointData=ballsMap[mapPointIndex]
var ballsAtTheMapPoint=ballsMap[mapPointIndex].balls;
var temperature;
if(ballsAtTheMapPoint.length>0)
{
temperature=balls[ballsAtTheMapPoint[ballsAtTheMapPoint.length-1]].temperature;
}else
{
temperature="none1";
}
var column,line=0;
while(line<scale)
{
column=0;
while(column<scale)
{
putTemperatureColorAt(temperature,(mapPointData.horizontalPosition*scale+column)*4+(mapPointData.verticalPosition*scale+line)*4*imgWidth*scale);
column++;
}
line++;
}
});
canvasContext.putImageData(ImgData,0,0);
}
function putTemperatureColorAt(temperature,index)
{
switch(Math.round(temperature))
{
case -5:
ImgData.data[index+0]=0;
ImgData.data[index+1]=255;
ImgData.data[index+2]=255;
ImgData.data[index+3]=255;
break;
case -4:
ImgData.data[index+0]=50;
ImgData.data[index+1]=255;
ImgData.data[index+2]=200;
ImgData.data[index+3]=255;
break;
case -3:
ImgData.data[index+0]=100;
ImgData.data[index+1]=255;
ImgData.data[index+2]=150;
ImgData.data[index+3]=255;
break;
case -2:
ImgData.data[index+0]=150;
ImgData.data[index+1]=255;
ImgData.data[index+2]=100;
ImgData.data[index+3]=255;
break;
case -1:
ImgData.data[index+0]=200;
ImgData.data[index+1]=255;
ImgData.data[index+2]=50;
ImgData.data[index+3]=255;
break;
case 0:
ImgData.data[index+0]=255;
ImgData.data[index+1]=255;
ImgData.data[index+2]=0;
ImgData.data[index+3]=255;
break;
case 1:
ImgData.data[index+0]=255;
ImgData.data[index+1]=200;
ImgData.data[index+2]=0;
ImgData.data[index+3]=255;
break;
case 2:
ImgData.data[index+0]=255;
ImgData.data[index+1]=150;
ImgData.data[index+2]=0;
ImgData.data[index+3]=255;
break;
case 3:
ImgData.data[index+0]=255;
ImgData.data[index+1]=100;
ImgData.data[index+2]=0;
ImgData.data[index+3]=255;
break;
case 4:
ImgData.data[index+0]=255;
ImgData.data[index+1]=50;
ImgData.data[index+2]=0;
ImgData.data[index+3]=255;
break;
case 5:
ImgData.data[index+0]=255;
ImgData.data[index+1]=0;
ImgData.data[index+2]=0;
ImgData.data[index+3]=255;
break;
case "none1":
ImgData.data[index+0]=0;
ImgData.data[index+1]=0;
ImgData.data[index+2]=0;
ImgData.data[index+3]=255;
break;
default:
console.log("Impossible to find color:"+temperature);
}
}
when i run the code, console say : "Impossible to find color: none1"
this means that temperature="none1" but if temperature="none1" the outpout of switch shouldn't be default cause there is case "none1":
case "none1":
ImgData.data[index+0]=0;
ImgData.data[index+1]=0;
ImgData.data[index+2]=0;
ImgData.data[index+3]=255;
break;
I very don't understand wath's wrong, i hope my english wasn't too bad.
Change your switch to the following:
switch (isFinite(temperature) ? Math.round(temperature) : temperature) {
// ...
}
You want to avoid rounding on a non-finite value aka an invalid Number.
Example
const process = (temperature) => {
switch (isFinite(temperature) ? Math.round(temperature) : temperature) {
case 0: return 'Zero';
case 1: return 'One';
case 'none1': return 'None';
default: throw new Error(`Unknown temperature: ${temperature}`);
}
};
console.log(process(0.2)); // Zero
console.log(process(0.8)); // One
console.log(process('none1')); // None
console.log(process(undefined)); // throw Error
Check your switch statement.
console.log(Math.round("none1"))

how i get out from the loop if switch case implemented(there is a switch inside the loop)

How I get out from the loop if switch-case implemented (there is a switch inside the loop).
function playInbestPlace() {
console.log("hello from playInbestPlace ")
findEmptyarea();
for (var i = 0; i < indexOfEmpty.length; i++) {
var elem = indexOfEmpty[i];
switch (elem) {
case 0:
cells[elem].childNodes[0].append("o");
break;
case 2:
cells[elem].childNodes[0].append("o");
break;
case 4:
cells[elem].childNodes[0].append("o");
break;
case 6:
cells[elem].childNodes[0].append("o");
break;
case 8:
cells[elem].childNodes[0].append("o");
break;
}
}
}
I want it to get out if any case valid.
you can add a variable found and break out of the loop if it's true :
function playInbestPlace() {
console.log("hello from playInbestPlace ")
findEmptyarea();
for (var i = 0; i < indexOfEmpty.length; i++) {
var elem = indexOfEmpty[i];
var found = false; // initial found is false
switch (elem) {
case 0:
cells[elem].childNodes[0].append("o");
found = true;
break;
case 2:
cells[elem].childNodes[0].append("o");
found = true;
break;
case 4:
cells[elem].childNodes[0].append("o");
found = true;
break;
case 6:
cells[elem].childNodes[0].append("o");
found = true;
break;
case 8:
cells[elem].childNodes[0].append("o");
found = true;
break;
}
if(found) // break out if it's true
break;
}
}
You could use a flag variable to break from the loop when some condition is verified.
function playInbestPlace() {
console.log("hello from playInbestPlace ");
findEmptyarea();
var keepOnLooping = true;
for (var i = 0; keepOnLooping && i < indexOfEmpty.length; i++) {
if (elem % 2 === 0) {
cells[elem].childNodes[0].append("o");
keepOnLooping = false;
}
}
}
I've also added epascarello optimization in my answer.

switch case js two parameters

Please tell me how I can do with two parameters and simplify this code to a normal state. Thank you! This logic is very necessary for me, I hope for your indulgence.
var treshhold_two = 0;
function Test(attack, ratio) {
switch (attack) {
case 0,01:
switch (ratio) {
case 2:
treshhold = 2798,6;
break;
case 4:
treshhold = 3678,16;
break;
case 6:
treshhold = 5757,12;
break;
}
break;
case >0,01:
switch (attack, ratio) {
case 0,03,2:
treshhold = -5,75712;
break;
case 0,03,4:
treshhold = -5,75712 * 1,1;
break; // -45%
case 0,03,6:
treshhold = -5,75712 * 0,96;
break; // -52%, and etc.
...
}
break;
}
}
Try:
var treshhold_two = 0;
function Test(attack, ratio) {
if(attack == 0,01) {
switch (ratio) {
case 2:
treshhold = 2798,6;
break;
case 4:
treshhold = 3678,16;
break;
case 6:
treshhold = 5757,12;
break;
}
}
else {
switch (attack) {
case 0,03:
if(ratio==2) treshhold = -5,75712;
if(ratio==4) treshhold = -5,75712 * 1,1;
if(ratio==6) treshhold = -5,75712 * 0,96;
break;
...
}
}
}
//option:1
var treshhold = 0;
function Test(attack, ratio) {
switch (attack) {
case 0,01:
if(ratio==2) treshhold = 2798,6;
if(ratio==4) treshhold = 3678,16;
if(ratio==6) treshhold = 5757,12;
break;
case 0,03:
if(ratio==2) treshhold = -5,75712;
if(ratio==4) treshhold = -5,75712 * 1,1;
if(ratio==6) treshhold = -5,75712 * 0,96;
break;
// ...
}
}
}
//option:2
var treshhold = 0;
function Test(attack, ratio) {
switch (attack) {
case 0,01:
switch (ratio) {
case 2: treshhold = 2798,6; break;
case 4: treshhold = 3678,16; break;
case 6: treshhold = 5757,12; break;
}
case 0,03:
switch (ratio) {
case 2: treshhold = -5,75712; break;
case 4: treshhold = -5,75712 * 1,1; break;
case 6: treshhold = -5,75712 * 0,96;; break;
}
// ...
}
}
//option:3
var treshhold = 1223456;
function Test(ratio, attack) {
switch (ratio) {
case 2:
switch (attack) {
case 0,01: ... break;
case 0,03: ... break;
case 0,1: ... break;
}
break;
case 4:
switch (attack) {
case 0,01: ... break;
case 0,03: ... break;
case 0,1: ... break;
}
break;
case 6:
switch (attack) {
case 0,01: ... break;
case 0,03: ... break;
case 0,1: ... break;
}
break;
}
// option?
var treshhold_two = 0;
function Test(attack, ratio) {
if (attack == 0.01) {
switch (ratio) {
case 2:
treshhold = 2798.6;
break;
case 4:
treshhold = 3678.16;
break;
case 6:
treshhold = 5757.12;
break;
}
}
else if (attack > 0.01) {
switch (attack, ratio) {
case 0,03,2: // what does it mean ?
treshhold = -5.75712;
break;
case 0,03,4: // what does it mean ?
treshhold = -5.75712 * 1.1;
break; // -45%
case 0,03,6: // what does it mean ?
treshhold = -5.75712 * 0.96;
break; // -52%, and etc.
...
}
}
}

how to return value from for loop each time

What I want to do is when I press on right key from keyboard return 100 and when I press again return 200 then 300 and so on...
function looptest() {
for (i = 100; i < 1000; i+=100) {
result+=i;
}
}
$(document).keydown(function (e) {
switch (e.which) {
case 37: // left
// do something
break;
case 38: // up
//do something
break;
case 39: // right
console.log(looptest());
break;
case 40: // down
//do something
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
This is my code and it returns every time 100, what's wrong in my code?
just do simply something like
var count= 100;
$(document).keydown(function (e) {
switch (e.which) {
case 37: // left
// do something
break;
case 38: // up
//do something
break;
case 39: // right
console.log(count)
count=count+100;
break;
case 40: // down
//do something
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
or if you want to use looptest() then change your function like below
count=0;
function looptest() {
count=count+100;
}
Assign K=0 in global space
$(document).keydown(function (e) {
switch (e.which) {
case 37: // left
// do something
break;
case 38: // up
//do something
break;
case 39: // right
K+=100
break;
case 40: // down
//do something
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
This code will add 100 to i everytime you press the right key of your keyboard.
var i = 0;
$(document).keydown(function (e) {
switch (e.which) {
case 37: // left
// do something
break;
case 38: // up
//do something
break;
case 39: // right
i = i+100;
console.log(i);
break;
case 40: // down
//do something
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
var result = 0;
function looptest() {
for (i = 100; i < 1000; i+=100) {
result =(result + i);
}
}
$(document).keydown(function (e) {
switch (e.which) {
case 37: // left
// do something
break;
case 38: // up
//do something
break;
case 39: // right
console.log(looptest());
break;
case 40: // down
//do something
break;
default:
return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
declare result globally
and while adding it is concating so please add them inside ()

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