Changing an image in a switch statement - javascript

I have an image in my HTML, but i would like to change the image when an answer is given by the user. For some reason the first function works, but the image doesn't change.. Can someone help me please.
This is my code so far:
window.onload = function () {
'use strict';
var showMessage = function (text) {
var messageCenter = document.getElementById('messageCenter');
messageCenter.innerHTML += "<p>" + text + "</p>\n";
};
var checkName = function (name) {
switch (prompt("What is your name?")) {
case "Leonard":
showMessage("Leonard! How did I not recognize you! Why would you like to get rid of me!");
break;
case "Penny":
showMessage("Penny Penny Penny! You've got so much to learn.");
break;
case "Howard":
showMessage("Howard, the only one without a Ph.D");
break;
case "Raj":
showMessage("Interesting. You're afraid of insects and women. Ladybugs must render you catatonic!");
break;
default:
showMessage("Well, I'm not familiair with you. I don't like to talk to strange people.");
break;
}
};
checkName()
var myImage = document.getElementById('sheldon');
var checkCase = function (img) {
switch (img) {
case "Leonard":
myImage("verbaasd.jpg");
break;
case "Penny":
myImage("les.jpg");
break;
case "Howard":
myImage("howard.jpg");
break;
case "Raj":
myImage("loser.jpg");
break;
default:
myImage("sheldon.jpg");
break;
}
};
checkCase()
};

Your error is in myImage(). You set this variable with a DOM object and call it as a normal function. This gives you an error. You also forgot to store the name and pass it as argument to your checking functions.
Your code should be:
window.onload = function () {
'use strict';
var name = prompt("What is your name?");
var showMessage = function showMessage(text) {
var messageCenter = document.getElementById('messageCenter');
messageCenter.innerHTML += "<p>" + text + "</p>\n";
};
var checkName = function (name) {
switch (name) {
case "Leonard":
showMessage("Leonard! How did I not recognize you! Why would you like to get rid of me!");
break;
case "Penny":
showMessage("Penny Penny Penny! You've got so much to learn.");
break;
case "Howard":
showMessage("Howard, the only one without a Ph.D");
break;
case "Raj":
showMessage("Interesting. You're afraid of insects and women. Ladybugs must render you catatonic!");
break;
default:
showMessage("Well, I'm not familiair with you. I don't like to talk to strange people.");
break;
}
};
checkName(name);
var myImage = function myImage(img) {
var sheldon = document.getElementById('sheldon');
sheldon.innerHTML = '<img src="' + img + '"/>';
};
var checkCase = function (name) {
switch (name) {
case "Leonard":
myImage("verbaasd.jpg");
break;
case "Penny":
myImage("les.jpg");
break;
case "Howard":
myImage("howard.jpg");
break;
case "Raj":
myImage("loser.jpg");
break;
default:
myImage("sheldon.jpg");
break;
}
};
checkCase(name);
};
Now your myImage() is a function which insert a new image inside a container with ID sheldon.
If you don't want to have a container for the image, and instead you want reference directly to the image, can change the myImage() function in:
var myImage = function myImage(img) {
var sheldon = document.getElementById('sheldon');
sheldon.src = img;
};
BTW, I see that you're learning so it's right to start from the basics, but remember that there are cleaner ways to do that.
Hope it's helpful to you.

Related

how to get the fetch method to work and the process after linking external data source?

i am a beginner at javascript, and i'm asked to build a dynamic image galleries with external data using the fetch() method for an assignment. the requirement for this is to use the fetch() method to link an image slider onto this main page, and i need to make a button to click where a random number is chosen and an external dataset is loaded. but i am having difficulty getting the code to work and i don't know how or where the mistake is, this code is given to me as an example and i need to revise it with my own external links. please help me!
this is what i have in javascript:
console.clear();
document.querySelector("button#myLanguageBTN").addEventListener(
"click",
function () {
var randomNumber = Math.floor(Math.random() * 5);
switch (randomNumber) {
case 1:
var myfetchLink = "https://codepen.io/tchau16/pen/PoaaJYG.js";
case 2:
var myfetchLink = "https://codepen.io/tchau16/pen/dyKKVGP.js";
case 3:
var myfetchLink = "https://codepen.io/tchau16/pen/jOKKGWZ.js";
case 4:
var myfetchLink = "https://codepen.io/tchau16/pen/JjZZrGQ.js";
default:
var myfetchLink = "https://codepen.io/tchau16/pen/dyKKVGP.js";
}
console.log(myfetchLink);
.then((response) => {
return response.text();
})
.then((myInformation) => {
const myReturn = JSON.parse(myInformation);
There are few mistakes in your code -
switch does not have a break statement, so it was falling to default statement every time.
Fetch was not used. Added console logs at appropriate places.
use let and const, removed var for myfetchLink.
use free apis to test your code.
Switch JS MDN link - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
Free apis - https://apipheny.io/free-api/#apis-without-key
console.clear();
document.querySelector("button#myLanguageBTN").addEventListener(
"click",
function() {
let randomNumber = Math.floor(Math.random() * 5);
let myfetchLink = '';
switch (randomNumber) {
case 1:
myfetchLink = "https://www.boredapi.com/api/activity";
break;
case 2:
myfetchLink = "https://catfact.ninja/fact";
break;
case 3:
myfetchLink = "https://api.publicapis.org/entries";
break;
case 4:
myfetchLink = "https://codepen.io/tchau16/pen/JjZZrGQ.js";
break;
default:
myfetchLink = "https://api.coindesk.com/v1/bpi/currentprice.json";
}
console.log(myfetchLink);
fetch(myfetchLink)
.then((response) => {
console.log(response);
return response.text();
}).then((myInformation) => {
console.log(myInformation);
const myReturn = JSON.parse(myInformation);
});
});
<button id="myLanguageBTN">Fetch the Data</button>

How to go to an a Specific HTML when a word is detected (Java)

Java I made an HTML called hello.html and now I want to use the replace() function in Java to go to the HTML page when the word "Covid" is detected on Google, I tried but it doesn't work for some reason, can you see where I am going wrong, or do I have to change my entire code?
function redirectURL() {
var specWord = getSpecificWord();
switch(specWord)
{
case 'corona':
window.location.replace('hello.html');
break;
case 'covid':
window.location.replace('hello.html');
break;
case 'covid-19':
window.location.replace('hello.html');
break;
default:
return true;
break;
}
return false; // don't let the form submit
}
function getSpecificWord(Element) {
var specificWord = "corona";
return specificWord;
}
The code does not work since you are not calling the redirectURL function.
Append redirectURL() to your code or use this instead:
(function redirectURL() {
var specWord = getSpecificWord();
switch (specWord) {
case 'corona':
window.location.replace('hello.html');
break;
case 'covid':
window.location.replace('hello.html');
break;
case 'covid-19':
window.location.replace('hello.html');
break;
default:
return true;
break;
}
return false; //don't let the form submit
})();
function getSpecificWord(Element) {
var specificWord = 'corona';
return specificWord;
}

javaScript: Split one function into two

I have the following working function (the lower part of it is not shown):
<script type="text/javascript">
function plan_click(clicked_id){
let var_plan;
let var_sgldbl;
var_sgldbl = 'sgl';
var_plan = clicked_id;
document.getElementById(clicked_id).style.background = "green";
/* new code*/
let var_tab01;
switch (var_plan) {
case '101':
var_tab01 = 201;
document.getElementById(var_tab01).style.background = "green";
break;
}}
</script>
I want the function to be split into two functions at the /new code/ - in separate scripts as the new "tabeller" function might be placed in a js.-file. The "tabeller"-function should be called from the plan_click-function and receive the actual values from the variables: var_plan and var_sgldbl.
Which code should be inserted to make the split effective?
Just move the code out to another function. var_plan should be a parameter, while var_tab01 can be the return value.
function plan_click(clicked_id) {
let var_plan;
let var_sgldbl;
var_sgldbl = 'sgl';
var_plan = clicked_id;
document.getElementById(clicked_id).style.background = "green";
let var_tab01 = tabeler(var_plan);
...
}
function tabeler(var_plan)
let var_tab01;
switch (var_plan) {
case '101':
var_tab01 = 201;
document.getElementById(var_tab01).style.background = "green";
break;
...
}
return var_tab01;
}

Function parameter not carried to switch statement in JavaScript

I've been making a basic game but I've encountered a problem while trying to make a function that would be usable among several occasions by using the switch statement. The output I keep getting when I run the function is the default code block. Here's some sample code:
function battle(boss) {
slaying = true;
while(slaying) {
switch(boss) {
case 'boss1':
console.log('This is' + boss1.name);
break;
case 'boss2':
console.log('This is' + boss2.name);
break;
default:
console.log('No boss');
break;
}
slaying = false;
}
}
function Boss(name) {
this.name = name;
}
var boss1 = new Boss('boss1');
var boss2 = new Boss('boss2');
battle(boss1);

Can I implement/put an array on a switch conditional?

I was building my code when came to my mind a bizarre idea, can I implement/put an array inside a switch?
I mean, how can I make the codeHide case work? with this piece of code it don't work.
When I ask to set the command and I put hide() (that is codeHide[0] on the codeHide array) I want to switch take the codeHide case (my if-statement) and return an alert telling me the alertMessage of that particular array element.
If I put hide(background) (that is codeHide[1] on the codeHide array) I want to switch take the codeHide case else (of my if-statement) and return an alert telling me the alertMessage of that particular array element(in the is-statement).
Hope you understand me.
Doing this it don't work and I think it's because the "case codeHide:".
And this is what I've done so far:
var codeHide = ['hide()', 'hide(background)'];
$(".code").on("click", function () {
var codePrompt = prompt("Set the code in the command line."),
alertMessage = "",
consoleMessage = "Used '" + codePrompt + "' command.";
switch (codePrompt) {
case codeHide:
if (codeHide[0]) {
alertMessage = "Hiding elements...";
} else {
alertMessage = "Hiding Background...";
}
break;
default:
alertMessage = consoleMessage = "We are sorry but you entered a WRONG command, try again tho!\ntyped: " + codePrompt;
break;
}
alert(alertMessage);
console.log(consoleMessage);
});
I think you are trying something like
var commands = {
hide: 'hide()',
hideBg: 'hide(background)'
};
var codePrompt = prompt("Set the code in the command line."),
alertMessage;
switch (codePrompt) {
case commands.hide:
alertMessage = "Hiding elements...";
break;
case commands.hideBg:
alertMessage = "Hiding Background...";
break;
default:
alertMessage = "WRONG command";
break;
}
}
However, you can also use
var commands = {
'hide()': "Hiding elements...",
'hide(background)': "Hiding Background..."
};
var codePrompt = prompt("Set the code in the command line.");
var alertMessage = commands[codePrompt] || "WRONG command";
I guess you also want to run some functions:
var commands = {
'hide()': {
text: "Hiding elements...",
funcion: someFunctionToHide
},
'hide(background)': {
text: "Hiding Background...",
funcion: someFunctionToHideBackground
}
};
var codePrompt = prompt("Set the code in the command line."),
command = commands[codePrompt];
if(!command) {
alertMessage = "WRONG command";
} else {
alertMessage = command.text;
command.function();
}
switch operates by comparing the value being switched on to each of the possible cases using the identity operator ===. This means that you can put an array inside a case, and it will work as specified (but certainly not very intuitively for arrays):
var x = [1];
var a = [1];
switch (x) {
case [1]: alert("it's [1]!"); break;
case a: alert("it's a!"); break;
case x: alert("it's x!"); break;
}
This will alert "it's x!", while you might be expecting that either of the preceding two cases would be "good enough" to trigger. But that's just how === works:
[1] === x // false
a === x // true
x === x // true
So while you can technically use an array, in practice it would be very unusual to have a situation where it's actually useful to do so.
Going back to your code, since the values you are interested in are strings it seems that using a simple object as a map would do just fine:
var commands = {
"hide()": {
alert: "Hiding elements...",
console: "Blah blah"
}.
"hide(background)": {
alert: "Hiding background...",
console: "Blah blah"
}.
};
var fallback = {
alert: "Sorry, wrong command",
console: "Sorry, wrong command"
};
which would then allow you to write
var result = commands[input] || fallback;
alert(result.alert);
console.log(result.console);

Categories

Resources