Im really trying to keep my code clean by using the switch statement but it seems its not working some how. I have made an array of objects that have the class .ClientButtonPic and if I write
var clientButtonNumber = $(".ClientButtonPic");
$(clientButtonNumber[0]).click(function(){ $(".ClientImages:eq(0)").fadeIn(300);
$(".ClientImages:eq(1)").fadeOut(300); });
It works fine but since I have 6 instances that can be clicked I wanted to use the switch statement. Heres my code:
var clientButtonNumber = $(".ClientButtonPic");
$(clientButtonNumber).click(function(){
switch(this)
{
case 0:
$(".ClientImages:eq(0)").fadeIn(300);
$(".ClientImages:eq(1)").fadeOut(300);
break;
case 1:
$(".ClientImages:eq(1)").fadeIn(300);
$(".ClientImages:eq(0)").fadeOut(300);
break;
default:
break;
}
});
Any help is appreciated.
You need to use the index of this.
switch( $(this).index(".ClientButtonPic") )
Related
I want to ask about switch case statement in javascript.
switch(ch){
case 0:
//do something, if condition match ,so go to case 2 and 3 (no need to go case 1)
//if not match, go to case 1, 2, and 3
break;
case 1:
//..
break;
case 2:
//..
break
case 3:
//...
}
In my code has 4 cases . There is a condition in case 0 that will skip case 1 and go to case 2. How can I do that?
The switch statement is an alternative to long if else statements (See the docs here). In your case, I believe that you should use the regular if statements.
// check if it passes case1
if (condition === case1) {
// check if it passes case1
if (condition === case2) {
// check if it passes case1
if (condition === case3) {
// do something here...
}
}
}
You may also use ternary operator, although it might be a bit hard to read as you add more conditions.
i think if else statement better suit your requirement. if you still want to do it in switch here's example :) :
var sw = function(cs){
switch(cs){
case 1:
console.log("case 1 !!!");
sw(3);
break;
case 2:
console.log("case 2 !!!");
break;
case 3:
console.log("case 3 !!!");
break;
}
};
sw(1);
I believe this's what you are looking for:
function Switcher(choice){
switch(choice){
case 1: console.log(1);;
case 4: console.log(4); break;
case 2: console.log(2); break;
case 3: console.log(3); break;
}
}
and then call Switcher(1) and see the O/P
I was looking at some logic related to switches in JavaScript today, the code I was looking at used a series of if and else statements however there were a bunch of shared logic cases which could be consolidated.
Additionally if and else statements are not exactly equal to switch statements because the runtime may implement them with jump tables making the order of execution faster than if and else.
Because you can only continue iteration patterns in ECMAScript you can hack up a solution which looks like jumping by encapsulating the logic in a fake loop like so:
(function(){
//In some function use this code
var test = 2;
Switch: while(true) switch(test){
case 2: test = 1; continue Switch;
case 1: test = 0; continue Switch;
default:alert(test);return;
};
//End code example
})();
The condition for while(true) can be changed to use another variable for state if you need to.
This gets the code as close to using jump tables as you can in other languages and a similar pattern can implement things like goto or duffs device
See also How can I use goto in Javascript?
Or Porting duff's device from C to JavaScript
Or this GIST https://gist.github.com/shibukawa/315765020c34f4543665
I'm making a little mini game and I have to put multiple switches inside of themselves, so I really need to know how to put a switch into a few words so I can make this game. I have tried it so that it's fully written out but it takes FOREVER and it is very confusing as to what is what. please help!
EDIT: im sorry i made this so confusing... let me say that again in english (: what i need to do is make it so when they either choose one of the cases or if they choose none of them (default) it would reactivate the switch. the way the person would choose is through a prompt. so what i thought i could do was make a switch into a variable then use that variable inside the switch basicly creating an endless thing that if they choose default it asks them again. here is an example i will post it in one minute
here you go!:
//this is the variable holding the switch
/*I I I I I*/
/*V V V V V*/
var switch1 = {
var choice = prompt("do you choose EXAMPLE or EXAMPLE").toUpperCase()
switch(choice) {
case 'EXAMPLE':
//this will repeat the whole prompt
switch1
break;
default:
//this will repeat it too
switch1
break; }
}
So how would i do this and make java accept this #ajaysinghdav10d?
JavaScript allows you to nest switch statements.
Have a look at this dummy example in which a service returns the location of the customer and his choice of product. Based on the combination of Choice and Location, a function to return the co-ordinates of the nearest store is called; I have used dummy values where ever necessary and alerts to explain the flow of control within the nested switch statements:
var choice = "CHO2"; /* call getChoice() function returning values from {CHO1, CHO2, ...}*/
var location = "LOC1"; /*call getLocality() function returning values from {LOC1, LOC2, ...}*/
switch (location) {
case "LOC1":
switch (choice) {
case "CHO1":
/* redirectToCHO1ofLOC1() is a function returning co-ordinates of the store*/
alert("redirectToCHO1ofLOC1");
break;
case "CHO2":
alert("redirectToCHO2ofLOC1");
break;
default:
alert("redirectToRegret");
break;
}
break;
case "LOC2":
switch (choice) {
case "CHO1":
/* redirectToCHO1ofLOC2() is a function returning co-ordinates of the store*/
alert("redirectToCHO1ofLOC2");
break;
case "CHO2":
alert("redirectToCHO1ofLOC2");
redirectToCHO2ofLOC2();
break;
default:
alert("redirectToRegret");
break;
}
break;
default:
alert("redirectToRegret");
break;
}
Updated answer based on the new context :
You must use recursion for that matter. Put your switch inside a function and call that function from the case statement of your switch, please have a look at this:
function recursiveSwitch() {
var choice = prompt("do you choose EXAMPLE or EXAMPLE").toUpperCase()
switch (choice) {
case 'EXAMPLE':
//this will repeat the whole prompt
recursiveSwitch();
break;
default:
//this will repeat it too
recursiveSwitch();
break;
}
}
Now just call the recursiveSwitch function from where ever you want and an endless loop would start.
this is my first post ever on stackoverflow! I am a front-end web developer enthusiast and novice...If I am breaching the stackoverflow etiquette or rules of the road please let me know or give me the smack down..
I am trying to evaluate class names in an array of elements. If the class name contains a certain value then I want to manipulate an attribute for that element.
First, I create an array of elements using jquery stored as a variable:
note that buttons class naming convention is "share_button_[social media service name]"
Next, I create a for loop to iterate through the buttons variable
Within the for loop I have switch statement - the purpose is to evaluate each element in the Buttons array and add an href attribute to the element if it meets a certain criteria
Putting it all together:
var buttons = $('a[class^="share_button"]');
for (i=0; i < buttons.length; i++) {
switch (true) {
case ($(buttons[i]).attr('[class*="twitter"]')):
console.log('twitter!');
break;
case ($(buttons[i]).attr('[class*="linkedin"]')):
console.log('linkedin!');
break;
case ($(buttons[i]).attr('[class*="facebook"]')):
console.log('facebook_like!');
break;
case ($(buttons[i]).attr('[class*="google_plusone"]')):
console.log('google_plusone!');
break;
case ($(buttons[i]).attr('[class*="reddit"]')):
console.log('reddit!');
break;
}
}
This does not seem to be working at all. Here is the codepen, http://cdpn.io/fKoak
Is it a good practice to loop through a jquery array of elements like this?
Should I be using the switch statement in this case and am I using it correctly? (there are more possible cases then I have case statements for and I have no default - I want the cases without a match to "do noting")
In this particular case, what i wrong with the formation of my code that the desired outcome is not happening?
I think it would be better to do something more like this.
var $buttons = $('a[class^="share_button"]');
var $twitterButtons = $('[class*="twitter"]', $buttons);
$twitterButtons.each(function(i, button) {
//Do stuff to the twitter button
});
var $linkedinButtons = $('[class*="linkedin"]', $buttons);
$linkedinButtons.each(function(i, button) {
//Do stuff to the linkedin button
});
var $facebookButtons = $('[class*="facebook"]', $buttons);
$facebookButtons.each(function(i, button) {
//Do stuff to the facebook button
});
var $google_plusoneButtons = $('[class*="google_plusone"]', $buttons);
$google_plusoneButtons.each(function(i, button) {
//Do stuff to the google_plusone button
});
var $redditButtons = $('[class*="reddit"]', $buttons);
$redditButtons.each(function(i, button) {
//Do stuff to the reddit button
});
Adding the second parameter to your selectors gives them a context. So $('[class*="twitter"]', $buttons) looks through $buttons and selects those with a class containing twitter
You can use jQuery's each() method to iterate over the elements, then check the className
$('a[class^="share_button"]').each(function(i, elem) {
if ( elem.className.indexOf('twitter') != -1 ) {
console.log('twitter');
}else if ( elem.className.indexOf('linkedin') != -1 ) {
console.log('linkedin');
}else if (..... etc
});
A better approach would be to keep the switch, but google_plusone kinda screws that up with the underscore, so you'd have to replace that with something else:
$('a[class^="share_button"]').each(function(i, elem) {
switch( elem.className.split('_').pop() ) {
case 'twitter' :
console.log('twitter');
break;
case 'linkedin' :
console.log('linkedin');
break;
case 'googleplusone' :
// you'll have to remove the underscore or just check for "plusone"
}
});
I ultimately decided to drop the for loop and use jquery .each method -http://api.jquery.com/each/ - that was recommended by #adeno above. The two solutions offered by #adeno using .each both work good but I finally chose to go with the jquery .is method https://stackoverflow.com/a/2240085 - http://api.jquery.com/is/ - since we decided to use .each method it is already a "jquery solution" so using .is method to evaluate if the class name of each element contained a certain value was a lot less code - and allowed for more flexibility then the proposed .indexOf and .split/.pop methods by #adeno in imo..
#Tom also gave a workable solution. However, although I didn't mention it specifically in my question, I wanted a solution that would use an iterator to go through the array of selected button elements.
var $buttons = $('a[class^="share_button"]');
$buttons.each(function(i,e){
switch (true) {
case ($(e).is('[class*="twitter"]')):
alert('yea! it\'s a twitter button - now do something');
break;
case ($(e).is('[class*="linkedin"]')):
alert('yea! it\'s a linkedin button - now do something');
break;
case ($(e).is('[class*="facebook"]')):
alert('yea! it\'s a faceboook button - now do something');
break;
case ($(e).is('[class*="google_plusone"]')):
alert('yeah! it\'s a google plus one button - now do something');
break;
case ($(e).is('[class*="reddit"]')):
alert('yea! it\'s a reddit one button - now do something');
break;
}
});
The situation I have is a drop down list and an image on a html page. I'm using javascript script. I'm using a switch statement. I've constructed my switch and case statements. So far I got an alert box for each case that displays a unique message in the browser when I make a selection in the drop down list. But I want the image on the page to change with each message. I tried using multiple variables in the switch parameter but that disables the alert boxes. Is there a way for me to use a single switch variable that can call the message boxes and the images? Or is there a way to use multiple variables in the switch parameter? I've been researching the internet, even this forum for answers, but haven't found anything that matches my problem. I found some answers using if statements and AJax but that is outside of the scope of my homework and what we've learned so far. So basically my task is to use a switch construct to evaluate the selection and when a match is found, display the appropriate image and the alert box. Any suggestions.
It doesn't sound like you need multiple variables in the switch expression. Rather, you need multiple statements in each branch of your switch. For example:
switch(selectedValue)
{
case 'foo':
alert('foo');
imageElement.src = 'http://foo';
break;
case 'bar':
alert('bar');
imageElement.src = 'http://bar';
break;
}
You can change the source of the image for each case. Switch statements only accept one parameter.
HTML
<img src="image_path" id="myImage" />
JavaScript
var img = document.getElementById( "myImage" );
switch( value ) {
case 0:
alert( "message" );
img.src = "new_path";
break;
case 1:
alert( "message" );
img.src = "new_path";
break;
default: break;
}
I want to use switch condition in JavaScript code. but i dont know how? please help me to do this.. thanks in advance
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
http://www.w3schools.com/js/js_switch.asp
You don't have a lot of detail in your question but I'll try to help regardless - but without knowing the full scenario its a bit hard to give you a definitive answer.
I'm going to assume you want to handle a redirection on a button click, but with some conditions?
Usually you would use a simple case statement to handle this (or an if/else if there is only two conditions), such as the following (using jQuery for event bindings):
<button id="button1">Button 1</button>
<button id="button2">Button 2</button>
<script type="text/javascript">
jQuery(function() {
jQuery("button1, button2").click(function(e) {
switch(jQuery(this).attr("id")) {
case "button1":
location.href = "http://clickedonbutton1.com";
break;
case "button2":
location.href = "http://clickedonbutton2.com";
break;
default:
alert("Dont know what happened here....");
}
});
});
</script>
Read switch
No restriction on case value type.
You can use "string" case value in JavaScript
You can add duplicate case value. The first matching case value is recognized, regardless of duplicates.
switch(youVariable)
{
case "test1":
break;
case "test2":
break;
default:
break;
}