OnClick function within a image button - javascript

I am trying to create a quiz game that allows the user to simply click on an image as their answer.
I
function checkimage(){
}
body{
font: 15px/1.5 Arial, Helvetica,sans-serif;
padding:0;
margin:50px;
background-color:rgba(255, 128, 0, 0.54);
text-align: center
}
h2{
padding: 10px;
background-color: red;
}
#container{
margin : 20px auto;
background-color: white;
height: 60%;
width : 100%;
border-radius: 5px;
box-shadow: 0px 5px 15px 0px;
position: relative;
}
*{
box-sizing: border-box;
}
.column{
float:left;
width:100%;
padding:5px;
}
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width">
<head>
<meta charset="UTF-8">
<title>Quiz</title>
<link rel="stylesheet" href="game.css">
</head>
<body>
<h1> Welcome to the Shopping Quiz Game</h1>
<div id="container">
<div class = "question">
<h2>which of the following is a fruit? click on the image </h2>
<div class = "quiz">
<div class="column">
<input type="image" id="forest" src="forest.jpg" style="width:50%"> </div>
<input type="image" id="snow" src="snow.jpg" style="width:50%"
onclick="checkimage"> </div>
</div>
</div>
<div>
<script src="game.js"></script>
</div>
</body>
</html>
have tried firstly to make the images into buttons which worked because they are clickable.However, i have very basic javascript knowledge and i am not able to do the "on-click" function that once the user clicks the image, the program will check if the image clicked is the right answer and then return a message.

You can get id value when an image got clicked and then you can compare with your original answer to check whether it's right or not.
function checkimage(element) {
var rightAns = "Apple";
if (element.id == rightAns) {
alert("You selected right ans!")
} else {
alert("You selected wrong ans!")
}
}
<h3>Which image is of an apple?</h3>
<input type="image" id="Apple" src="https://www.organicfacts.net/wp-content/uploads/apple.jpg" style="width:25%;height:25%;" onclick="checkimage(this)"></div>
<input type="image" id="Watermelon" src="https://snaped.fns.usda.gov/sites/default/files/styles/crop_ratio_7_5/public/seasonal-produce/2018-05/watermelon.jpg?itok=6EdNOdUo" style="width:25%;height:25%;" onclick="checkimage(this)"></div>
Note that here i am passing reference of an image element to the
javascript function on click event like
'onclick="checkimage(this)"' where 'this' is a reference.

Hello this is simple if i understood correctly, you need to use hidden values in your html code for example:
//OPTION 1:
<img src="IMAGE_PATH_HERE" onClick='answerIs('id_here_or_answer_here')'/>
//OPTION 2:
using hidden values
<input type='hidden' value='id_here_or_answer' id='answer_{id should be unique}'/>
Finally if you are using a loop you could use any option with uniques ID in order to make it work:
function checkimage(id){
$answer = $('#answer_'+id).val().toString;
}
//or while//
for ($i; $i>=10; $i++){
//input or image as you wish
//<inputs OR <img TAGS
<input type='hidden' value='id_here_or_answer' id='answer_<?= $i; ?>' onClick='checkimage('<?= $i; ?>');return false;'/>
}
//end//
in fact, you are telling to the JS what ID is the real answer even if you have a lot of options
USAGE in your case:
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width">
<head>
<meta charset="UTF-8">
<title>Quiz</title>
<link rel="stylesheet" href="game.css">
<script>
$( document ).ready(function() {
console.log( "ready!" );
function checkimage(value){
alert('answer is:' + value);
if (value == "apple"){
//do something
}else{
//optionally do something here too
}
}
});
</script>
</head>
<body>
<h1> Welcome to the Shopping Quiz Game</h1>
<div id="container">
<div class = "question">
<h2>which of the following is a fruit? click on the image </h2>
<div class = "quiz">
<div class="column">
<input type="image" id="forest" src="forest.jpg" style="width:50%" onClick="checkimage('apple');return false;"> </div>
<input type="image" id="snow" src="snow.jpg" style="width:50%"
onClick="checkimage('banana');return false;"> </div>
</div>
</div>
<div>
<script src="game.js"></script>
</div>

function checkimage(id){
$answer = $('#answer_'+id).val().toString;
}
//or while//
for ($i; $i>=10; $i++){
//input or image as you wish
<inputs OR <img TAGS
<input type='hidden' value='snow' id='snow_<?= $i; ?>' onClick='checkimage('<?= $i; ?>');reuturn false;'/>
}
//end//
body{
font: 15px/1.5 Arial, Helvetica,sans-serif;
padding:0;
margin:50px;
background-color:rgba(255, 128, 0, 0.54);
text-align: center
}
h2{
padding: 10px;
background-color: red;
}
#container{
margin : 20px auto;
background-color: white;
height: 60%;
width : 100%;
border-radius: 5px;
box-shadow: 0px 5px 15px 0px;
position: relative;
}
*{
box-sizing: border-box;
}
.column{
float:left;
width:100%;
padding:5px;
}
<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width">
<head>
<meta charset="UTF-8">
<title>Quiz</title>
<script>function checkimage(value)</script>
<link rel="stylesheet" href="test.css">
</head>
<body>
<h1> Welcome to the Shopping Quiz Game</h1>
<div id="container">
<div class = "question">
<h2>which of the following is a fruit? click on the image </h2>
<div class = "quiz">
<input type="image" id="snow" src="snow.jpg" style="width:50%" onclick="checkimage('snow');return false;"></div>
<input type="image" id="forest" src="forest.jpg" style="width:50%" onclick="checkimage('forest');return True;"> </div>
</div>
<div>
<script src="test.js"></script>
</div>
</body>
</html>

Related

Background color not getting updated by updating CSS variables using JS [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
In the JavaScript section, I have updated the variables such as spacing for padding, blur for making the image blur and basec for changing the background color of the image including the color of span tag in heading which is JS. The background color of the image is not at all Updating.
Rest All are working properly. Please look into the JavaScript section and please tell why basec variable is not changing.
const inputs = document.querySelectorAll('.controls input');
function update() {
// console.log(this.value);
const suffix = this.dataset.sizing || '';
// console.log(suffix);
// console.log(this.name);
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
}
inputs.forEach(input => input.addEventListener('change', update));
inputs.forEach(input => input.addEventListener('mousemove', update));
* {
margin: 0;
padding: 0;
background-color: cadetblue;
font-family: sans-serif;
font-size: 1.5rem;
}
:root {
--spacing: 10px;
--blur: 1px;
--basec: #ffe591;
}
body {
text-align: center;
color: aliceblue;
}
.controls {
margin: 40px;
}
img {
padding: var(--spacing);
filter: blur(var(--blur));
background: var(--basec);
}
.h1 {
color: var(--basec);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS variables updation</title>
<link rel="stylesheet" href="controls.css">
</head>
<body>
<h2>Updating CSS variables using <span class="h1">JS</span></h2>
<div class="controls">
<label for="spacing">Spacing :</label>
<input type="range" name="spacing" id="spacing" min="10" max="200" value="10" data-sizing="px">
<label for="blur">Blur :</label>
<input type="range" name="blur" id="blur" min="1" max="30" value="10" data-sizing="px">
<label for="base">Base Color</label>
<input type="color" name="base" id="base" value="#ffe591">
</div>
<img src="https://picsum.photos/id/0/500/500" alt="an image">
<script src="cssvar.js"></script>
</body>
</html>
There was a typo in variable name,
It has to be base but you have named it basec in css.
Tip: You would probably want to use input event rather than change for inputs as change event might not show live changes.
const inputs=document.querySelectorAll('.controls input');
function update(){
// console.log(this.value);
const suffix=this.dataset.sizing || '';
// console.log(suffix);
// console.log(this.name);
document.documentElement.style.setProperty(`--${this.name}`,this.value+suffix);
}
inputs.forEach(input=>input.addEventListener('input',update));
inputs.forEach(input=>input.addEventListener('mousemove',update));
*{
margin:0;
padding:0;
background-color: cadetblue;
font-family: sans-serif;
font-size: 1.5rem;
}
:root{
--spacing:10px;
--blur:1px;
--base:#ffe591;
}
body{
text-align: center;
color: aliceblue;
}
.controls{
margin: 40px;
}
img{
padding:var(--spacing);
filter: blur(var(--blur));
background: var(--base);
}
.h1{
color:var(--basec);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS variables updation</title>
<link rel="stylesheet" href="controls.css">
</head>
<body>
<h2>Updating CSS variables using <span class="h1">JS</span></h2>
<div class="controls">
<label for="spacing">Spacing :</label>
<input type="range" name="spacing" id="spacing" min="10" max="200" value="10" data-sizing="px">
<label for="blur">Blur :</label>
<input type="range" name="blur" id="blur" min="1" max="30" value="10" data-sizing="px">
<label for="base">Base Color</label>
<input type="color" name="base" id="base" value="#ffe591">
</div>
<img src="https://picsum.photos/id/0/500/500" alt="an image">
<script src="cssvar.js"></script>
</body>
</html>

Access a Variable within a function in Javascript

I want to Check the woodCount Variable if it is equal to or greater than 25 I want to have a new button appear on the page. For now I just had it console.log true or false.
Sorry if this is really easy or makes no sense but I am new to Javascript. Thanks!
JAVASCRIPT FILE
var woodCount = 0;
var gatherWood = document.getElementById("gatherWood");
var wood = document.getElementById("wood");
gatherWood.onclick = function(){
woodCount++;
wood.innerHTML = woodCount;
}
function fire() {
if woodCount >= 25 {
console.log('True');
}else{
console.log('False');
}
}
HTML FILE
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Game</title>
<meta name="description" content="Game">
<meta name="author" content="SitePoint">
<script src="game.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<input class="woodbtn" type="button" value="Gather Wood" id="gatherWood" />
Wood = <span id="wood">0</span>
</div>
</body>
</html>
Add a button to the DOM and keep it hidden. When it exceeds the threshold, toggle the display property from hidden to block.
Make sure we call the function where the toggling of style happens in the onclick event handler where incrementation occurs.
var woodCount = 0;
var gatherWood = document.getElementById("gatherWood");
var wood = document.getElementById("wood");
gatherWood.onclick = function() {
woodCount++;
wood.innerHTML = woodCount;
fire();
};
function fire() {
if (woodCount >= 25) {
document.getElementById("higherThan25")
.style.display = "block";
} else {
//console.log("False");
}
}
.woodbtn {
border-style: solid;
border-color: white;
color: white;
padding: 10px 10px;
text-align: center;
font-size: 13px;
cursor: pointer;
float: right;
background-color: transparent;
}
.woodtxt {
text-color: white;
}
body {
background-color: black;
color: white;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Game</title>
<meta name="description" content="Game">
<meta name="author" content="SitePoint">
<script src="game.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<input class="woodbtn" type="button" value="Gather Wood" id="gatherWood" />
<input style="display: none;" class="woodbtn" type="button" value="Higher Than 25" id="higherThan25" />
Wood = <span id="wood">0</span>
</div>
</body>
</html>

dynamic progress bar from textbox

Working on a site for my Pen and Paper style RPG and i want to be able to update the health bars on the fly. Been looking around and found some stuff to update a progess bar by check boxes but not text boxes and i just cant figure out how to do it. Ideally id also like to make the progress bar a custom design but right now i just want to get it to work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)">
<meta name="dcterms.created" content="Tue, 12 Mar 2019 18:08:09 GMT">
<meta name="description" content="">
<meta name="keywords" content="">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<title>Health</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
.tasks{
background-color: #F6F8F8;
padding: 10px;
border-radius: 5px;
margin-top: 10px;
}
.tasks span{
font-weight: bold;
}
.tasks input{
display: block;
margin: 0 auto;
margin-top: 10px;
}
.tasks a{
color: #000;
text-decoration: none;
border:none;
}
.tasks a:hover{
border-bottom: dashed 1px #0088cc;
}
.tasks label{
display: block;
text-align: center;
}
</style>
</head>
<body>
<div class="progress progress-striped active">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
</div>
</div>
<input name="done" class="done" type="textbox" id="txtJob" value="99">
<script>
var valeur = document.getElementsByName('txtJob')[0].value
$('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);
//});
</script>
</body>
Looks like you've got most of it. You're just left with initialization and event binding.
// Create function for updating the progress bar
function update(target) {
var valeur = $(target).val();
$('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);
}
// Use that function to initialize the progress bar
update($('#txtJob'));
// Add event handlers so that changes to the textbox update the progress bar
$('#txtJob').on('change keyup', event => update(event.currentTarget));
There are a few questions I have regarding the goal. Are you wanting only one text box to determine the length of the progress bar? And if so, is that length based on someone entering digits 0-100?
If that is your goal, then you are almost there. I would move a few things around and model the code like this. First I imported a more up-todate version of jQuery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Then I updated the HTML markup to include the classes mentioned in the CSS and updated the javascript to use jQuery, since you had imported it already, we should use it :)
<body class="tasks">
<div class="progress progress-striped active">
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
</div>
</div>
<input name="done" class="done" type="textbox" id="txtJob" value="0">
<script>
$(function () {
$('#txtJob').keyup(function(){
var valeur = $('#txtJob').val();
$('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);
});
});
</script>
</body>

Trouble with Show/Hide code, second level

I cannot for the life of me figure out why the text under Sub1 and Sub2, do not show the text under them, when clicking them. Only the first link "Main Category" functions. It is making me enter more description, though the issue is already explained the best I know how.
<!DOCTYPE html>
<?php
session_start();
print "
<html>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#body {
font-family: 'Helvetica', Arial, sans-serif;
display:none;
width: 100%;
padding: 5px 0;
text-align: left;
background-color: lightblue;
margin-top: 5px;}
</style>
</head>
<body>
<div id="body12">
Main Category</font>
<div class='showArticle'>
Sub1</font>
<div class='showComments'>
<font size="+1" color="red"><b>Text1</b></font>
</div><br>
Sub2</font>
<div class='showComments'>
<font size="+1" color="red"><b>Text2</b></font>
</div></div><br>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js' type='text/javascript'></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.showArticle').hide();
$('.articleTitle').show();
$('.showComments').hide();
$('.commentTitle').show();
$('.articleTitle').click(function(e){
$(this).next('.showArticle').slideToggle();
e.preventDefault();
});
$('.commentTitle').click(function(e){
$(this).next('.showComments').slideToggle();
e.preventDefault();
});
});
</script>
</body>
</html>
You have a typo in your JS $('.commentsTitle').click(...
In the html you assigned the class commentsTitle, in the JS, you referred to commentTitle.
$(document).ready(function(){
$('.showArticle').hide();
$('.articleTitle').show();
$('.showComments').hide();
$('.commentsTitle').show();
$('.articleTitle').click(function(e){
$(this).next('.showArticle').slideToggle();
e.preventDefault();
});
$('.commentsTitle').click(function(e){
$(this).next('.showComments').slideToggle();
e.preventDefault();
});
});
<body>
<div id="body12">
Main Category</font>
<div class='showArticle'>
Sub1</font>
<div class='showComments'>
<font size="+1" color="red"><b>Text1</b></font>
</div><br>
Sub2</font>
<div class='showComments'>
<font size="+1" color="red"><b>Text2</b></font>
</div></div><br>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js' type='text/javascript'></script>
</body>
</html>

Javascript dont take changing from textarea

I want to take all the HTML from a div container, to put it in a value in hidden field and then to show it to the users with the same CSS style but without textareas tags.
Instead of textareas, I want to show the value which came from the text fields (textarea)! So far so good!
But when a change the information in textareas my javascript code do not take the new information from that field.
What is wrong with my code?
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<?php
if(isset($_POST['save'])){
$scrita = $_POST['hid'];
$scritaInsert = strip_tags($scrita, '<p><n><nz><font><bl><br><r><chh>');
echo $scritaInsert;
exit; //just for the test
}
?>
<form method="POST">
<input type="submit" name="save" class="btn-style" value="Save" id="submitContainer"/>
<input type="hidden" name="hid" id="hid"/>
</form>
<div id="container">
<p style="text-align: center;font-weight: bold;font-size: 23px;color: black;">CocaCola</p>
<p style="text-align: center; color: black; font-size:16px; text-decoration: underline;">
The address
</p>
<p style="font-weight: bold; color: black;">
To: <textarea name="do" style="width: 920px; max-width: 100%; height: 18px;">CocaCola Company</textarea>
</p>
<p style="font-weight: bold; color: black;">
Attention: <textarea name="vnimanieto" style="width: 830px; max-width: 100%; height: 18px;">CocaCola Company</textarea>
</p>
<p style="text-align: center;font-weight: bold;font-size: 19px;color: black;">
CONTRACT<br>
<n style="text-align: center;font-size: 16px;color: black;">
For transport
</n><br>
<nz style="text-align: center;">№<textarea name="nomer" style="width: 60px; max-width: 100%; height: 18px;">1737</textarea>
Date:<textarea name="date" style="width: 90px; max-width: 100%; height: 18px;" id="date">25.05.2016</textarea>
</nz>
</p>
</div>
</body>
</html>
<script type="text/javascript">
$('#submitContainer').click(function(){
$('.picker').html('');
var content = $('#container').html();
$('#hid').val(content);
});
</script>
I think your problem could be the type of html slashes:
Try:
String.prototype.stripSlashes = function(){
return this.replace(/\\(.)/mg, "$1");
}
$('#submitContainer').click(function(){
$('.picker').html('');
var content = $('#container').html();
$('#hid').val(content.stripSlashes());
});
I have changed my JavaScript to the following code and it's now working properly:
<script type="text/javascript">
$('#submitContainer').click(function(){
$('.picker').html('');
$("textarea").each(function() {
$(this).text($(this).val());
});
var content = $('#container').html();
$('#hid').val(content);
});
</script>
I think you should be using the method text() not html(), because html() will just copy all the text including the HTML tag, but text() will only copy the real text.
Check out this fiddle.

Categories

Resources