Javascript array and image [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Okay so I've asked this question before but I didn't get the answer that solved my problem, I'll try to explain it better. So let say I have a array with 3 items and let say it landed on 0 I have a code set up for which it will display in div now I need the image to be displayed right next to the array that is displayed. So another example would be like I have an array of cars, BMW, civic, and Mercedes and let say I have a random number generator and it chooses 1 which is bmw the word will be displayed in the div and if the civic was picked the civic will has a civic logo next to it and if Mercedes was picked Mercedes will have a logo next to it. Also if possible I want the id added in I'll put the CSS of background-image to what ever the pic is(reasoning is I want to add some design in the picture)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<ul id="carList">
</ul>
<button id="getRandomCar">Get Random Car</button>
</body>
<script>
$(document).ready( function(){
var carsArray = [{
brand : 'BMW',
logo : 'link-to-logo.png',
model : 'BMW X7',
},
{
brand : 'Honda',
logo : 'link-to-logo.png',
model : 'Civic',
},
{
brand : 'Mercedez-Benz',
logo : 'link-to-logo.png',
model : 'C-Class Sedan',
}];
function randomNumberGenerator(params) {
return Math.round(Math.random()*params);
}
function randomCar() {
$('#getRandomCar').click( function() {
var selectedCar = randomNumberGenerator(carsArray.length - 1);
console.log(selectedCar);
var template = '<li>';
template += 'Brand: ' + carsArray[selectedCar].brand + '</br>';
template += 'Logo: ' + carsArray[selectedCar].logo + '</br>';
template += 'Model: ' + carsArray[selectedCar].model + '</br>';
$('#carList').html(template);
} );
}
randomCar();
});
</script>
</html>
Try this as a reference.
I've created an array of objects (carsArray). Since it's an object, you can add properties that you think necessary.
The sample generates a random number, then use it as index for the carsArray. The acquired object values will be injected into a DOM.

Related

I'm trying to increase a value when clicking and value returning NaN [duplicate]

This question already has answers here:
why the result is NaN?
(4 answers)
Closed 1 year ago.
I've tried a lot of stuff, however I don't know any JavaScript. All of the JavaScript in the code is copied from stack overflow and other sources. The only thing I know how to use is HTML and I'm still very new. (it might also include some CSS which I also don't know at all)
The <!--<button id="bigButton" onclick="bigBottlePress()"><img src="Images/BigBottle.png"></button>--> is a failed thing so ignore it lol.
<html>
<head>
<meta charset="utf-8">
<title>Bottle Clicker</title>
</head>
<body>
<img src="Images/BigBottle.png" height="500">
<!--<button id="bigButton" onclick="bigBottlePress()"><img src="Images/BigBottle.png"></button>-->
<br>
<br>
<input type="text" id="hydrationLevelDisplay" placeholder="Hydration Level: " disabled style= text-align:center>
<script>
var hydrationLevel = 0
function bigBottlePress() {
var hydrationLevel = hydrationLevel + 1
document.getElementById("hydrationLevelDisplay").value = "Hydration Level: " + hydrationLevel;
document.title = "Hydration Level: " + hydrationLevel;
}
</script>
</body>
</html>
You have already declared hydrationLevel outside function, so don't need to redclare it. Just change,
var hydrationLevel = hydrationLevel + 1
to
hydrationLevel = hydrationLevel + 1
create a button -> id:btn
create a result div or p or h1 -> id:hydrationLevel
select the button, add event listener
document.getElementById('btn').addEventListener('click', incrementLevel)
let hydrationCount = 0;
function incrementLevel() {
hydrationCount += 1;
document.getElementById('hydrationLevel').textContent = hydrationCount;
}
I'd encourage you to use event listeners this way. not inline that's why I provided this solution.

i need help please check if anything is wrong with the program and please help me correct it [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
<!Doctype html>
<html>
<title>JavaScript Tutorial</title>
<body>
<script language = "javascript">
var cleanCities = ["Cheyenne ","Santa Fe ","Tucson ","Great Falls ","Honolulu"];
var cityToCheck = "Tucson";
if(cityToCheck === cleanCities[i]) {
alert("You are clean");
}
</script>
</body>
</html>
I cannot find the errors
it's a javascript code
<!Doctype html>
<html>
<title>JavaScript Tutorial</title>
<body>
<script language = "javascript">
var cleanCities = ["Cheyenne ","Santa Fe ","Tucson ","Great Falls ","Honolulu"];
var cityToCheck = "Tucson";
if(cityToCheck === cleanCities[i]) {
alert("You are clean");
}
</script>
</body>
</html>
It says there is some problem in line 14
Where is your for loop for which you're an index i? If its removed intentionally then Tucson in your array has a space in the end. Use trim method.
Also language = "javascript" is wrong, its usually type="text/javascript"
The code should be like below:
enter code here
var cleanCities = ["Cheyenne ","Santa Fe ","Tucson ","Great Falls ","Honolulu"];
var cityToCheck = "Tucson";
for(var i=0; i<cleanCities.length; i++) {
if(cityToCheck === cleanCities[i].trim()){
alert('you are clean');
}
}

How do I get the answer to the random flash-card by clicking the panel?

I am trying to make a random flash card type of generator for javascript syntax. When i hit the random question button, it will display a random question such as "What is a variable?" but on clicking the panel, it should display the answer out of the answer array. All of the answers are in an object. I am 3 months new to programming, so any advice is appreciated.
$('button').on('click', function(){
var ranQuestion = Math.floor(Math.random()* arrOfQuestions.length);
$('#panel').html(arrOfQuestions[ranQuestion]);
//produce answer in the panel html onclick
$('#panel').on('click', function(){
var pan = $('#panel').html();
if(pan === arrOfQuestions){
$('#panel').html(test);
}
})
})
enter link description here
I'd suggest using an array of objects to store your Q&A data
var questions = [
{
question: 'What is a variable?',
answer: 'A variable is a container...'
},
{
question: 'Function',
answer: 'etc etc'
}
];
//produce a random flashcard question from the arrOfQuestions array
$('button').on('click', function() {
var ranQuestion = Math.floor(Math.random() * questions.length);
$('#panel').html(questions[ranQuestion].question);
//produce answer in the panel html onclick
$('#panel').on('click', function(){
var pan = $('#panel').html();
if(pan === questions[ranQuestion].question){
$('#panel').html(questions[ranQuestion].answer);
}
})
})
You are pretty much get there. Please try this out.
var cards = {
varQuestion: 'a variable is a container for a type of value',
fun: 'A function runs a block of code when it is called',
cond: 'a conditional statement runs a block of code if something is true, and can run another block of code if not.'
}
var arrOfQuestions = [[ 'varQuestion', 'What is a Variable' ],
[ 'fun', "What is a function" ],
[ 'cond', "What is a conditional statement" ]];
//produce a random flashcard question from the arrOfQuestions array
$('button').on('click', function(){
var ranQuestion = Math.floor(Math.random()* arrOfQuestions.length);
$('#panel').html(arrOfQuestions[ranQuestion][1]);
//produce answer in the panel html onclick
$('#panel').on('click', function(){
$('#panel').html(cards[arrOfQuestions[ranQuestion][0]]);
})
})
.w3-col{
height:300px;
text-align:center;
margin-left:34%;
}
img{
height:300px;
}
<html>
<title>javascript flash cards</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<div class="w3-container w3-center">
<h3>javascript flash cards</h3>
<p>choose a random flash-card, then click the panel for the answer. <button>Click for Random Question</button>
</p>
</div>
<br>
<div class="w3-row-padding">
<div class="w3-col s4 w3-yellow w3-padding-32" id='panel'>
<img src="https://scontent.felp1-1.fna.fbcdn.net/v/t1.0-9/12645111_1075109299208404_1425810696977443472_n.jpg?oh=9067c4ea98ee0335a2bbd9e0f50eccfa&oe=5B4DF254" style="width:100%">
</div>
</div>
</body>
</html>

Adding html table to javascript using document.write

Looking for some help here. Our class instructor is asking us to add a table into javascript using the document.write, I know this is not the recommended way to do this, but this is what our instructor is looking for:
Add code to the writeIt function that writes the opening table tag before iterating thru the heros and villians and then the closing table tag. Then modify the makeListItem to return a string in the form of tr td Hero td td Villan /td /tr.
I tried this but am getting a blank html page when try to view.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
<meta charset="utf-8" />
<script>
var superData = {"Super Man":["Lex Luther"],
"Bat Man":["Joker", "Riddler",],
"Spider Man":["Green Goblin",
"Vulture", "Carnage"],
"Thor":["Loki", "Frost Giants"]};
function writeIt('<table>'){
for (hero in superData){
var villains = superData[hero];
for (villainIdx in villains){
var villain = villains[villainIdx];
var listItem = makeListItem(<tr><td>Hero</td><td>Villan</td></tr>);
document.write(listItem);
}
}
}
function makeListItem(name, value){
var itemStr = "<li>" + name + ": " + value + "</li>";
return itemStr;
}
document.write('</table>');
</script>
</head>
<body onload="writeIt()">
</body>
</html>
Try this:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
<meta charset="utf-8" />
<script>
var superData = {
"Super Man": ["Lex Luther"],
"Bat Man": ["Joker", "Riddler", ],
"Spider Man": ["Green Goblin",
"Vulture", "Carnage"
],
"Thor": ["Loki", "Frost Giants"]
};
function writeIt() {
document.write('<table>');
for (hero in superData) {
document.write("<tr><td>" + hero + ": <ul>");
var villains = superData[hero];
for (villainIdx in villains) {
var villain = villains[villainIdx];
var listItem = makeListItem(villain);
document.write(listItem);
}
document.write("</ul></td></tr>");
}
}
function makeListItem(value) {
var itemStr = "<li>" + value + "</li>";
return itemStr;
}
document.write('</table>');
</script>
</head>
<body onload="writeIt()">
</body>
</html>
I tried this but am getting a blank html page when try to view.
Because you have syntax problems. Use F12 or the Inspector/Developer mode to find out why.
Our class instructor is asking us to add a table into javascript using the document.write, I know this is not the recommended way to do this, but this is what our instructor is looking for
True, it's often frowned upon, but JavaScript makes it available for a reason, so let's use it.
The first problem is that you seem to have transposed some code...
For example, you have function writeIt('<table>'). I think you meant document.write('<table>');.
function writeIt(){
document.write('<table>');
Next, you have your final document.write outside of your function call.
document.write('</table>');
This should be inside writeIt(), just after your for loop.
Finally, you have some unquoted stuff in your loop...
makeListItem(<tr><td>Hero</td><td>Villan</td></tr>);
Should be (single or double quotes):
makeListItem('<tr><td>Hero</td><td>Villan</td></tr>');
But that's still a bit off for a table. For example, Superman has a 1:1 ratio with his villains and Batman has a 1:2 ratio. You should be adding your rows and tables in a more predictable manner, but the above will at least start to give you output to work from.
Finally, an observation is that your makeListItem needs to use <ul> before it uses <li> so those problems need to be resolved. For now, I recommend you just spit the data out and format it later.

Creating a css class with a Javascript object or var [duplicate]

This question already has answers here:
How to dynamically create CSS class in JavaScript and apply?
(17 answers)
Closed 5 years ago.
Is it possible to create a css class based on a javascript object or variable?
An example would be if you had an input where you can enter a hex code. I can extract the value using javascript and set it to a var.
I can then use this var to set inline styles with javascript thus changing the color of text on the page. However is there a way I could use this var and create a css class? Rather than go through all the elements of the page and set the color, I'd rather add a class on one element of the page that then have the styles nested within that class to cascade to other elements.
Lots of ways to dynamically alter css styling after page load.
If you want to make a change that is applied as if it was a normal css script you can add a style tag to the header via javascript.
eg.
var color = "blue" ; // from your input
var element = document.createElement("style");
element.id = "myStyleId" ; // so you can get and alter/replace/remove later
element.innerHTML = ".myClass {color:" + color + ";}" ; // css rule
var header = document.getElementsByTagName("HEAD")[0] ;
header.appendChild(element) ;
Something like this buddy?
https://jsfiddle.net/BillyG83/hcek46a1/2/
made just for you, happy Friday
here is the code
<!DOCTYPE html>
<html>
<head>
<title>Test HTML</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="textBox"/>
<input type="button" id="submit" value="Go"/>
</body>
<script type="text/javascript">
$("#submit").click(function(){
var textBoxValue = $("#textBox").val();
if (textBoxValue.length == 0) {
alert("you didnt enter a value");
} else if (textBoxValue.length < 6) {
alert("you only entered " + textBoxValue.length + " chacters, a HEX code needs 6");
} else if (textBoxValue.length == 6) {
var newHEXcode = "#" + textBoxValue;
alert("new HEX code = " + newHEXcode)
} else {
alert("you only entered " + textBoxValue.length + " chacters, thats too many, a HEX code needs 6");
}
});
</script>
</html>
In this example if you enter hex value like FFFF00 or 800000 or FF0000 then it will change the background css of the text Hello Pratik Ghag!.
$("#txtInput").change(function(){
var color = "#"+$("#txtInput").val();
$(".spnMessage").css("background",color);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter hex color code:</p>
<input id="txtInput" /><br>
<span class="spnMessage">Hello Pratik Ghag!</span>

Categories

Resources