Switch with random not working - javascript

This is my current jScript code:
(modified STILL doesn't work)
function changeBG(){
document.getElementById('imgbox').src = switch(eval(rand())){
case 1: "img/img3.jpg";
break;
case 2: "img/img2.jpg";
break;
case 3: "img/img3.jpg";
break;
case 4: "img/img4.jpg";
break;
case 5: "img/img5.jpg";
break;
default: "img/background.jpg";
break;
}
}
function rand(){
return (Math.ceil((Math.random()*10)/2));
}
my HTML:
<input id="BGchange" type="button" onclick="changeBG()" value=">"/>
If I do something like this:
document.getElementById('imgbox').src = "img/img1.jpg";
It just works: I click on my button, the image changes, no problem. Fact is I want the image to change to a random one between 5 each time the button is clicked; to do this I wanted to use a switch that works with a random choice inside it.
What is wrong with my coding?! :( (I cant use jQuery or anything, just pure javascript, html and css, thats what the professor said at least)
Thank you <3

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
The switch-statement "executes" your Strings ("img/imgX.jpg") instead of returning them, so you may want put the switch in a function and then do
case 1: return "img/img3.jpg";
...
and keep in mind that each case of a switch statement must be terminated with break, otherwise the following case-Blocks will be executed as well!

Your function return an integer, while your switch case is looking for a string.
Remove quotes from the switch cases and everything should work.
function changeBG(){
document.getElementById('imgbox').src = switch(rand()){
case 1: "img/img3.jpg";
break;
case 2: "img/img2.jpg";
break;
case 3: "img/img3.jpg";
break;
case 4: "img/img4.jpg";
break;
case 5: "img/img5.jpg";
break;
default: "img/background.jpg";
}
}

Related

JS - Evaluation with function within switch-case

I have objects with ids like alternative1, alternative2 etc. I want to style all of these the same way so I'm trying:
switch (feature.id) {
case 'marker':
...
break;
case feature.id.includes('alternative'):
case 'connectionMarker':
... //add styling
break;
This does not seem to work. How could I do this?
You can use a simple trick:
switch (feature.id) {
case 'marker':
...
break;
case (feature.id.includes('alternative') ? feature.id : !feature.id):
// your code here
break;
case 'connectionMarker':
...
break;
}
Since feature.id is always a string value, !feature.id will always return false. Hence, if feature.id includes "alternative" this line:
case (feature.id.includes('alternative') ? feature.id : !feature.id):
becomes:
case feature.id:
which will always be the case (as feature.id === feature.id). Otherwise, the line evaluates to:
case 0:
which will be skipped by the interpreter.

Is it possible to do something on all switch cases by default without repeating?

Is there a way to repeat a sentence inside of a switch for every case but for default? Without repeating the action inside every case, of course.
I have this:
this.set_estate = function(state){
switch(state){
case 'LOADING':
current= est[state];
break;
case 'WRITING':
current= est[state];
//statements_2
break;
case 'WAITING':
current= est[state];
//statements_3
break;
default:
console.log('tried to set state: '+state);
break;
}
}
And I'd like to know if it could be shifted into something similar to:
this.set_estate = function(state){
switch(state){
case 'LOADING':
case 'WRITING':
case 'WAITING':
current= est[state];
continue;
case 'LOADING':
//statements_1
break;
case 'WRITING':
//statements_2
break;
case 'ESPERANDO':
//statements_3
break;
default:
console.log('tried to set state: '+state);
break;
}
}
Write another switch statement before this to do just the common lines. This would prevent you from writing the code multiple times, if that is your concern.

windows.location.pathname not working

I'm having issue with one of my cases not working. They all work except for one, which actually has queries in the URL, but they are always the same. The query URL looks like this: http://mywebsite.com/search/?q=label:Web-Design|label:Graphic-Design|label:Identity-Design|label:Brand-Design
It's not working and I'm wondering if windows.location supports queries in URL. It seems to me it wouldn't matter, but either way I cannot get this working.
I'm 100% positive that is the correct pathname, as I copied & pasted it, only to remove the domain just like the rest.
This is what I am using:
<script type='text/javascript'>
$(document).ready(function(){
switch (window.location.pathname) {
default:
$('.nav-blog').addClass('current');
break;
case '/p/about.html':
$('.nav-about').addClass('current');
break;
case '/':
$('.nav-home').addClass('current');
break;
case '/search/blog':
$('.nav-blog').addClass('current');
break;
case '/p/forums.html':
$('.nav-forums').addClass('current');
break;
case '/search/?q=label:Web-Design|label:Graphic-Design|label:Identity-Design|label:Brand-Design':
$('.nav-design').addClass('current');
break;
case '/p/photography.html':
$('.nav-photography').addClass('current');
break;
case '/p/hosting.html':
$('.nav-hosting').addClass('current');
break;
}
});
</script>
Change the variable in the switch to include the query string
$(document).ready(function(){
switch (window.location.pathname + window.location.search) {
default:
$('.nav-blog').addClass('current');
break;
case '/p/about.html':
$('.nav-about').addClass('current');
break;
case '/':
$('.nav-home').addClass('current');
break;
case '/search/blog':
$('.nav-blog').addClass('current');
break;
case '/p/forums.html':
$('.nav-forums').addClass('current');
break;
case '/search/?q=label:Web-Design|label:Graphic-Design|label:Identity-Design|label:Brand-Design':
$('.nav-design').addClass('current');
break;
case '/p/photography.html':
$('.nav-photography').addClass('current');
break;
case '/p/hosting.html':
$('.nav-hosting').addClass('current');
break;
}
});
However this will not match against the other cases if they have querystrings on the end, also currently your switch statement is case sensitive, you should probably toUpperCase() or toLowerCase() your switch.
This should fix most of your issues:
$(document).ready(function(){
var path = window.location.pathname.toLowerCase();
if(path == '/search/')
{
if(window.location.search.toLowerCase() == '?q=label:web-design|label:graphic-design|label:identity-design|label:brand-design')
$('.nav-design').addClass('current');
else
$('.nav-blog').addClass('current');
}
else
{
switch (path) {
default:
$('.nav-blog').addClass('current');
break;
case '/p/about.html':
$('.nav-about').addClass('current');
break;
case '/':
$('.nav-home').addClass('current');
break;
case '/search/blog':
$('.nav-blog').addClass('current');
break;
case '/p/forums.html':
$('.nav-forums').addClass('current');
break;
case '/p/photography.html':
$('.nav-photography').addClass('current');
break;
case '/p/hosting.html':
$('.nav-hosting').addClass('current');
break;
}
}
});
You should do even more sanitization of your inputs (window.location.path, window.location.search) than I am here like trimming them (removing leading and trailing whitespace) and removing the leading and trailing slashes etc.
Also what happens if for some reason your query string values are in a different order?
Things like this can happen for instance someone emails a link and it has a extra space at the end or somewhere in the query string, when the recipient clicks the link they may go to the right page but your switch will hit the default.

Is there a way to use IgnoreCase in Javascript?

I want to transnlate some words, but i have problems when I write HOUSE in uppercase or mixing. it just work when i write in lowercase
<script>
var translate = prompt("Enter one of the next words:\nhouse\ntable\ndog\ncat");
switch (translate){
case 'house': document.write("casa");
break;
case 'table': document.write("mesa");
break
case 'dog': document.write("perro");
break;
case 'cat': document.write("gato");
break;
default: document.write("Error");
}
</script>
Modified code. (As solution already given in comments. )
<script>
var translate = prompt("Enter one of the next words:\nhouse\ntable\ndog\ncat") || ''; // take '' if user cancel the prompt as it return `null`;
translate = translate.toLowerCase();
switch (translate){
case 'house': document.write("casa");
break;
case 'table': document.write("mesa");
break
case 'dog': document.write("perro");
break;
case 'cat': document.write("gato");
break;
default: document.write("Error");
}
</script>
Use something like toLowercase()
mystr="Hello WORLD !";
document.write(mystr.toLowerCase());
would give "hello world"
apply this to your translate variable
Ref : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/toLowerCase

JavaScript comma separation not working with switch case

In case of comma separation not working with swtich case. is there any way to do this?
switch(test)
{
case 0,1://not working it take last one (1)
"test"
break;
case 2,3://not working it take last one (3)
"test2"
break;
case 4,5://not working it take last one (5)
"test3"
break;
}
How can i add further number with each case?
switch(test)
{
case 0: case 1:
"test"
break;
case 2: case 3:
"test2"
break;
case 4: case 5:
"test3"
break;
}
You should fall through (which is considered a bad practice)
switch(test)
{
case 0:
case 1://not working it take last one (1)
"test"
break;
case 2:
case 3://not working it take last one (3)
"test2"
break;
}

Categories