Radio input onclick function won't run - javascript

I know the pictures don't show up, but that's not the issue. The text after the inputs won't show because the function won't restart. Do radio buttons support onclick? Thanks for the help! I am now adding this text because the site won't let me post this question unless I add more text. Sorry.
var gameContainer = document.getElementById("game-container");
var speechBox = document.createElement("DIV");
speechBox.id = "speech-box";
var speechP = document.createElement("P");
speechP.id = "speech-p"
var speech = document.createTextNode("");
var speechNum = 0;
var text = true;
function startGame() {
var startButton = document.getElementById("start-button");
gameContainer.removeChild(startButton); //button disappears
var logo = document.createElement("IMG");
logo.src = "index/src/img/logo.gif";
gameContainer.appendChild(logo);
logo.id="logo"; //logo appears
var sublogo = document.createElement("P");
var sublogoText = document.createTextNode("Yellow Diamond Version");
sublogo.appendChild(sublogoText);
gameContainer.appendChild(sublogo);
sublogo.id="sub-logo";
var sublogoImg = document.createElement("IMG");
sublogoImg.src = "index/src/img/yellowDiamondFace.png"
gameContainer.appendChild(sublogoImg);
sublogoImg.id = "sub-logo-img";
setTimeout(preLogoFade,3000);
function preLogoFade() {
var logoOpacity = .9;
var logoInterval = setInterval(function(){LogoFade()},100);
function LogoFade() {
logo.style.opacity=logoOpacity;
sublogo.style.opacity=logoOpacity;
sublogoImg.style.opacity=logoOpacity;
logoOpacity-=.1;
if(logoOpacity<=0){
gameContainer.removeChild(logo);
gameContainer.removeChild(sublogo);
gameContainer.removeChild(sublogoImg);
clearInterval(logoInterval);
setTimeout(mainMenu,200);
}
} //LogoFade Func End
} //preLogoFade Func End
} //startGame Func End
function mainMenu() {
var mainMenuBox = document.createElement("DIV");
mainMenuBox.id = "main-menu-box";
var mainMenuBoxNew = document.createElement("P");
mainMenuBoxNew.className = "main-menu-box-p";
mainMenuBoxNew.innerHTML = "New Game";
var mainMenuBoxNewPic = document.createElement("IMG");
mainMenuBoxNewPic.className = "main-menu-box-pic";
mainMenuBoxNewPic.src = "index/src/img/red.gif"
mainMenuBoxNew.appendChild(mainMenuBoxNewPic);
mainMenuBoxNew.onmouseenter = function(){mainMenuBoxNewPic.src = "index/src/img/redAnimated.gif";}
mainMenuBoxNew.onmouseleave = function(){mainMenuBoxNewPic.src = "index/src/img/red.gif";}
mainMenuBoxNew.onclick = function(){mainMenuNewFunc();}
function mainMenuNewFunc() {
gameContainer.removeChild(mainMenuBox);
preProfessorOpen();
}
var mainMenuBoxSave = document.createElement("P");
mainMenuBoxSave.className = "main-menu-box-p";
mainMenuBoxSave.innerHTML = "Save Code";
var mainMenuBoxSavePic = document.createElement("IMG");
mainMenuBoxSavePic.className = "main-menu-box-pic";
mainMenuBoxSavePic.src = "index/src/img/binary.jpg";
mainMenuBoxSave.appendChild(mainMenuBoxSavePic);
mainMenuBoxSave.onmouseenter = function(){mainMenuBoxSavePic.src = "index/src/img/binaryAnimated.gif";}
mainMenuBoxSave.onmouseleave = function(){mainMenuBoxSavePic.src = "index/src/img/binary.jpg";}
var mainMenuBoxCheat = document.createElement("P");
mainMenuBoxCheat.className = "main-menu-box-p";
mainMenuBoxCheat.innerHTML = "Cheat Code";
var mainMenuBoxCheatPic = document.createElement("IMG");
mainMenuBoxCheatPic.className = "main-menu-box-pic";
mainMenuBoxCheatPic.src = "index/src/img/cheatCode.jpg";
mainMenuBoxCheat.appendChild(mainMenuBoxCheatPic);
mainMenuBoxCheat.onmouseenter = function(){mainMenuBoxCheatPic.src = "index/src/img/cheatCodeAnimated.gif";}
mainMenuBoxCheat.onmouseleave = function(){mainMenuBoxCheatPic.src = "index/src/img/cheatCode.jpg";}
gameContainer.appendChild(mainMenuBox);
mainMenuBox.appendChild(mainMenuBoxNew);
mainMenuBox.appendChild(mainMenuBoxSave);
mainMenuBox.appendChild(mainMenuBoxCheat);
}
function preProfessorOpen() {
document.body.style.backgroundImage = "url(index/src/img/professor.png)";
gameContainer.appendChild(speechBox);
speechBox.appendChild(speechP);
speechP.innerHTML = "Welcome to the world of Pokémon, clod!";
speechBox.onclick = function(){professorOpen();}
function professorOpen() {
speechNum++;
switch(speechNum) {
case 1:
speech = "I am Yellow Diamond – reduced to introducing Pokémon Spin-Offs.";
break;
case 2:
speech = "This world of clods is widely inhabited by creatures known as Pokémon.";
break;
case 3:
speech = "These mysterious creature can be found in every corner of this world...";
break;
case 4:
speech = "Some run across the plains, others fly through the skies, and others yet swim deep in the oceans...";
break;
case 5:
speech = "Clods live together with these Pokémon, lending their little strength to one another to live and prosper.";
break;
case 6:
speech = "Let's get started with some quick questions...<br>Are you a boy? Or are you a girl?<br>(Probably a boy if Alex shared this with you.)";
break;
case 7:
speechBox.onclick = ""
speechBox.innerHTML = '<br> \
<input type="radio" class="gender-inpt" id="male" name="gender"> \
<label for="male" class="gender-lbl" id="male-lbl">Boy</label> \
<br> \
<input type="radio" class="gender-inpt" id="female" name="gender"> \
<label for="female" class="gender-lbl" id="female-lbl">Girl</label>'
document.getElementsByClassName("gender-inpt").onclick = function(){genderFunc();}
document.getElementsByClassName("gender-lbl").onclick = function(){genderFunc();}
function genderFunc() {
window.inptM = document.getElementById("male");
professorOpen();
}
break;
case 8:
speechBox.onclick = function(){professorOpen();}
speechBox.innerHTML = "";
speechBox.appendChild(speechP);
if(inptM.checked) {gender="boy";} else {gender="girl";}
speech = "So, you're a " + gender + "?";
}
if(text){speechP.innerHTML = speech;};
text = true;
} //professOpen Func End
} //preProfessOpen Func End
body {
background-color:black;
background-repeat:no-repeat; background-size:300px 700px; background-position:center top;
}
#game-container{
width:800px; height:700px;
border:1px solid white;
margin:0 auto;
overflow:hidden;
padding:0;
}
#start-button{
width:100px; height:40px;
position:relative; top:330px; left:350px;
background-color:red;
border:1px solid white; border-bottom-width:2px; border-top-width:0px;
font-size:125%;
cursor:pointer;
}
#start-button:hover{
color:white;
}
#logo{
width:100%; height:300px;
position:relative;
z-index:3;
}
#sub-logo{
text-shadow: 1px 0 5px white, -1px 0 5px white, 0 1px 5px white, 0 -1px 5px white;
color:#FEFF00;
text-align:center;
font-size:50px;
position:relative; bottom:70px; left:15px;
z-index:2;
}
#sub-logo-img{
width:550px; height:405px;
margin:auto;
position:relative; left:140px; bottom:170px;
z-index:1;
}
#main-menu-box{
width:200px;
margin:0 auto;
border:1px solid #444444; border-radius:4px;
position:relative; top:300px;
cursor:pointer;
}
.main-menu-box-p{
border-radius:4px;
background-color:#EEEEEE;
border:1px solid #666666;
padding-left:20px; padding-top:3px;
margin:0; margin-bottom:1px;
}
#speech-box{
width:60%; height:100px;
background-color:white;
color:black;
font-size:125%;
border:1px solid #999999; border-radius:20px;
margin:0 auto;
padding:0 10px;
opacity:.8;
position:relative; bottom:10px; top:600px;
cursor:pointer;
-webkit-touch-callout:none;
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}
.main-menu-box-pic{
width:20px; height:20px;
float:right;
position:relative; bottom:3px;
}
.gender-inpt{
float:left;
margin-right:10px;
}
#male-lbl{color:#0000FF;}
#female-lbl{color:#FF0066;}
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<title>Game</title>
<meta name="robots" content="noindex, nofollow">
<meta name="author" content="Some Nerd.">
<link rel="icon" href="http://pokeadventuretime.blogspot.com.br/favicon.ico">
<link rel="stylesheet" href="index/src/style.css">
</head>
<body>
<div id="game-container">
<button id="start-button" onclick="startGame()">Start</button>
</div>
<script src="index/src/src.js"></script>
</body>
</html>

Few things here. First of all, getElementsByClassName returns an array-like object, so it's basically a list of all the elements it found with that class. If you want to set an onclick, you need to pick a specific element or you will just be trying to set an onclick on the list which does nothing.
Secondly, you already have a the code which you want executed upon click wrapped up in a function (genderFunc) so there's no need to wrap it up again. so what you want to do here is:
var inputList = document.getElementsByClassName("gender-inpt")
for( var i = 0; i< inputList.length; i++){
inputList[i].onclick = genderFunc;
}
Alternately, you're already generating the html for the radio buttons dynamically so you could just set the onclick there:
speechBox.innerHTML = '
<br> \
<input type="radio" class="gender-inpt" id="male" name="gender" onclick "genderFunc"> \
<label for="male" class="gender-lbl" id="male-lbl">Boy</label> \
<br> \
<input type="radio" class="gender-inpt" id="female" name="gender" onclick "genderFunc"> \
<label for="female" class="gender-lbl" id="female-lbl">Girl</label>'

Related

How to return Google App Script result to external web page?

I found a GAS that will search a column for an ID number that has been entered to a Google Sheet by means of an HTML form. Once the ID# is found it will check a date in a different column and will return a message based on the date in the column relative to today's date. When I run the GAS I get the message returned to me from the result of the script but what I am looking to do is return the result of the script back to the webform to notify a user of the message after they submit the form. It doesn't have to be a GAS ... if anyone can do the same with Javascript I am all ears. Thanks in advance.
I have already tried to figure out how to call on the GAS from the html page but have had no success.
GAS:
<!-- Search Sheet for Bottle Expiration date -->
var ss = SpreadsheetApp.openByUrl("GSURL");
var sheet = ss.getSheetByName("Entries");
function doGet(e){
return search(e) ;
}
function doPost(e){
return search(e) ;
}
function search(e){
var id = e.parameter.last_name;
var values = sheet.getRange(2, 2, sheet.getLastRow(),sheet.getLastColumn()).getValues();
for(var i = 0;i<values.length; i++){
if(values[i][0] == id ){
i=i+2;
var name = sheet.getRange(i,4).getValue();
var hydroDate = Date.now()+14;
var hydroalert = ContentService.createTextOutput("Bottle is due for Hydro").setMimeType(ContentService.MimeType.TEXT)
if (hydroDate <= name)
return hydroalert;
}
}
return ContentService.createTextOutput("Id not found").setMimeType(ContentService.MimeType.TEXT);
}
HTML Page
<!DOCTYPE html>
<html>
<head><meta name="viewport" content="width=device-width, initial-scale=1" />
<title>UFD Tour 2 Monthlies</title>
<!-- <link rel="stylesheet" type="text/css" href="style.css" media="screen, handheld"/> -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js?rev=<?php echo time();?>"></script>
<script type="text/javascript" src="ufd_tour_2_monthlies.js?rev=<?php echo time();?>"></script>
<script type="text/javascript" src="qrscan.js?rev=<?php echo time();?>"></script>
<script src="https://rawgit.com/sitepoint-editors/jsqrcode/master/src/qr_packed.js">
</script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<!-- Place this within the <head> tag or just before the end of your <body> tag. -->
<script src="https://awesome-table.com/AwesomeTableInclude.js"></script>
</head>
<style>
h2 {
text-align: center;
}
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
.cancelbtn {
padding: 14px 20px;
background-color: #f44336;
}
.cancelbtn,.signupbtn {
float: left;
width: 50%;
}
.container {
padding: 16px;
}
.clearfix::after {
content: "";
clear: both;
display: table;
}
#media screen and (max-width: 300px) {
.cancelbtn, .signupbtn {
width: 100%;
}
}
.form_container { width: 90%; max-width:450px; margin:20px 30px 40px 30px; padding:15px 20px; font-size:15px; line-height:25px; text-align:left; background:#EBEBEB; }
.form_field { display:block; width:100%; height:30px; margin:5px 0px 10px 0px; padding:0px 10px; color:#333; font-size:16px; border:1px solid #999; border-radius:3px; -webkit-appearance:none; }
.form_button { display:block; width:100%; height:35px; margin:20px 0px; padding:0px 0px; color:#FFF; font-size:16px; font-weight:bold; border:1px solid #3E7998; border-radius:3px; background:#3E7998; -webkit-appearance:none; }
.form_message { }
body, input {font-size:14pt}
input, label {vertical-align:middle}
.qrcode-text { display:block; width:90%; height:30px; margin:5px 0px 10px 0px; padding:0px 10px; color:#333; font-size:16px; border:1px solid #999; border-radius:3px; -webkit-appearance:none; }
.qrcode-text-btn { display:block; text-align:center; width:90%; height:35px; margin:20px 0px; padding:0px 0px; color:#FFF; font-size:16px; font-weight:bold; border:1px solid #3E7998; border-radius:3px; background:#3E7998; -webkit-appearance:none; }
.qrcode-text-btn > input[type=file] {position:absolute; overflow:hidden; width:1px; height:1px; opacity:0}
</style>
<body>
<h2>Tour 2 Monthlies</h2>
<div class="container">
<form id="sheets" name="sheets" class="form_body">
<label for="first_name">Date</label>
<input id="first_name" name="first_name" type="date" class="form_field" value="" placeholder="Select Date"/>
<label for="last_name">Bottle Number</label>
<input id="last_name" name="last_name" class="form_field" onfocus="this.value='';" value="" placeholder="Select here to scan or enter manually"/>
<input type="button" name="btnScanBarcode" id="btnScanBarcode" class="form_button" value="Scan Bottle" onclick="javascript:openQRCamera(this);"></button>
<!-- <input id="last_name" name="last_name" type=text placeholder="Select here to scan or enter manually" class="qrcode-text"><label class="qrcode-text-btn"><input type=file accept="image/*" capture=environment onclick="openQRCamera(this);" tabindex=-1>Scan Bottle</label>
<script>function openQRCamera(node) {
var reader = new FileReader();
reader.onload = function() {
node.value = "";
qrcode.callback = function(res) {
if(res instanceof Error) {
alert("No QR code found. Please make sure the QR code is within the camera's frame and try again.");
} else {
node.parentNode.previousElementSibling.value = res;
}
};
qrcode.decode(reader.result);
};
reader.readAsDataURL(node.files[0]);
}</script> -->
<script>
function startBarcodeScanner()
{
window.location.href = 'bwstw://startscanner?field=last_name';
}
</script>
<label for="email">Bottle Location</label>
<select id="email" name="email" class="form_field" value="" placeholder="Bottle Location"/>
<option>ENGINE 1</option>
<option>ENGINE 2</option>
<option>ENGINE 3</option>
<option>SQUAD 4</option>
<option>SQUAD 41</option>
<option>LADDER 1</option>
<option>TRUCK 1</option>
<option>TRUCK 2</option>
<option>TRUCK 3</option>
<option>ENGINE 5</option>
<option>ENGINE 6</option>
<option>ENGINE 7</option>
<option>RESCUE 1</option>
<option>RESCUE 2</option>
<option>RESCUE 3</option>
<option>STATION 1 SPARE</option>
<option>STATION 2 SPARE</option>
<option>STATION 3 SPARE</option>
<option>SPECIAL OPS</option>
<option>BC</option>
<option>COD</option>
<option>DC</option>
<option>EMSC</option>
<option>FINV</option>
<option>COMM</option>
<option>TRAIN</option>
<option>BOAT</option>
<option>SPARE MASK</option>
<option>O/S</option>
<option>OTHER LOCATION</option>
<option>OTHER VEHICLE</option>
</select>
<input id="gs_code" name="gs_code" type="hidden" class="" value="=VLOOKUP(B:B,HydroBottles,4,FALSE)" placeholder=""/>
<div class="clearfix">
<input id="submit" name="submit" type="button" class="form_button" value="Enter Bottle" onClick="submit_form(); document.getElementById('last_name').value = ''; playAudio()"/>
<audio id="beep">
<source src="bleep.mp3" type="audio/mpeg">
</audio>
<div class="form_message" id="message">
<script>
var gs_hydrosearch = 'https://script.google.com/macros/s/AKfycby0VsXuYk-dODBhKpL-zFUeb5xI79Y8jGR0e20I/exec?id=gs_field';
var gs_field = ['last_name'];
function HydroSearch() {
doPost(
</script>
</div>
</div>
</div>
<!-- Place this tag where you want the Awesome Table Widget to render -->
<div data-type="AwesomeTableView" data-viewID="-LfNI2wu42vUdIl5oy9c"></div>
</form>
</body>
</html>
JS file that sends the data from the form to the Google Spreadsheet:
function submit_form() {
// Check Fields
var complete = true;
var error_color = '#FFD9D9';
var fields = ['first_name','last_name','email','gs_code'];
var row = '';
var i;
for(i=0; i < fields.length; ++i) {
var field = fields[i];
$('#'+field).css('backgroundColor', 'inherit');
var value = $('#'+field).val();
// Validate Field
if(!value) {
if(field != 'message') {
$('#'+field).css('backgroundColor', error_color);
var complete = false;
}
} else {
// Sheet Data
row += '"'+value+'",';
}
}
// Submission
if(complete) {
// Clean Row
row = row.slice(0, -1);
// Config
var gs_sid = 'GSID'; // Enter your Google Sheet ID here
var gs_clid = 'Client ID'; // Enter your API Client ID here
var gs_clis = 'API Client Secret'; // Enter your API Client Secret here
var gs_rtok = '0Auth RT'; // Enter your OAuth Refresh Token here
var gs_atok = false;
var gs_url = 'https://sheets.googleapis.com/v4/spreadsheets/'+gs_sid+'/values/Entries!A1:append?includeValuesInResponse=false&insertDataOption=INSERT_ROWS&responseDateTimeRenderOption=SERIAL_NUMBER&responseValueRenderOption=FORMATTED_VALUE&valueInputOption=USER_ENTERED';
var gs_body = '{"majorDimension":"ROWS", "values":[['+row+']]}';
// HTTP Request Token Refresh
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.googleapis.com/oauth2/v4/token?client_id='+gs_clid+'&client_secret='+gs_clis+'&refresh_token='+gs_rtok+'&grant_type=refresh_token');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
var response = JSON.parse(xhr.responseText);
var gs_atok = response.access_token;
// HTTP Request Append Data
if(gs_atok) {
var xxhr = new XMLHttpRequest();
xxhr.open('POST', gs_url);
xxhr.setRequestHeader('Content-length', gs_body.length);
xxhr.setRequestHeader('Content-type', 'application/json');
xxhr.setRequestHeader('Authorization', 'OAuth ' + gs_atok );
xxhr.onload = function() {
if(xxhr.status == 200) {
// Success
$('audio#beep')[0].play();
$('#message').hide().html("Bottle has been Entered! Scan next Bottle.").fadeIn().delay('1000').fadeOut().delay('7000');
}
else {
// Fail
$('#message').html('<p>Row Not Added</p><p>Response:<br/>'+xxhr.responseText+'</p>');
}
};
xxhr.send(gs_body);
}
};
xhr.send();
}
}
The answer to your question is encapsulated in this documentation It's called client to server communication. Presently your question is far to broad you need to do more research and perhaps some of your own debugging. I also recommend that you take this opportunity to take the [tour] and learn how to [ask] and [mcve].

How to create a button to move back and forth in JavaScrtipt

Good afternoon, everyone.
I'm a newbie in JavaScript, in general in coding. I want to create a "simple" app to move back and forth in a group of texts. With my little knowledge, I could get here, but it didn't work. any help will be highly appreciated.
document.getElementById("botonatras").addEventListener("click", next);
function next () {
var array = ["text1", "text2", "text3"];
var currentText = 0;
var textMax = 3;
currentText = (currentText + 1) %textMax;
document.getElementById("demo").innerHTML = currentText;
}
.demo {
height: 200px;
width:300px;
background-color:lightblue;
font-family:tahoma;
text-align:center;
font-size:18px;
}
.boton{
width:200px;
height:50px;
border:solid;
border-radius:5px;
background-color: rgba(255,90,18,0.5);
border-color:red;
color:white;
}
<html>
<body>
<p>Aplicacion para realizar lecturas de aplicacion.</p>
<button id="botonatras" class ="boton">Atras</button>
<button id="myBtn" class ="boton">Adelante</button>
<p class = "demo" id="demo"></p>
</body>
</html>
I did a three things to your code:
moved currentText = 0 and the declaration of array outside your next function's scope and into the global scope.
moved the part that displayed the new text into its own function
called the display function when the page loads with window.onload
document.getElementById("botonatras").addEventListener("click", next);
var currentText = 0;
var array = ["text1", "text2", "text3"];
function display () {
document.getElementById("demo").innerHTML = array[currentText];
}
function next () {
var textMax = 3;
currentText = (currentText + 1) % textMax;
display();
}
window.onload = function () {
display();
}
.demo {
height: 200px;
width:300px;
background-color:lightblue;
font-family:tahoma;
text-align:center;
font-size:18px;
}
.boton{
width:200px;
height:50px;
border:solid;
border-radius:5px;
background-color: rgba(255,90,18,0.5);
border-color:red;
color:white;
}
<html>
<body>
<p>Aplicacion para realizar lecturas de aplicacion.</p>
<button id="botonatras" class ="boton">Atras</button>
<button id="myBtn" class ="boton">Adelante</button>
<p class = "demo" id="demo"></p>
</body>
</html>
Define the variable currentText at a level above
document.getElementById("botonatras").addEventListener("click", next);
var currentText = 0;
function next () {
var array = ["text1", "text2", "text3"];
var textMax = 3;
currentText = (currentText + 1) %textMax;
document.getElementById("demo").innerHTML = currentText;
}
.demo {
height: 200px;
width:300px;
background-color:lightblue;
font-family:tahoma;
text-align:center;
font-size:18px;
}
.boton{
width:200px;
height:50px;
border:solid;
border-radius:5px;
background-color: rgba(255,90,18,0.5);
border-color:red;
color:white;
}
<html>
<body>
<p>Aplicacion para realizar lecturas de aplicacion.</p>
<button id="botonatras" class ="boton">Atras</button>
<button id="myBtn" class ="boton">Adelante</button>
<p class = "demo" id="demo"></p>
</body>
</html>

How to get onmouseover and onmouseout settings to work as desired?

The Issue
I have a shopping cart for an online store and to view the contents of the shopping bag you hover over a div in the navigation menu. I made a prototype where the shoppingTab div actually touched the trolley div in the navigation bar that made it appear upon hovering. This then allowed me to move my cursor from the shoppingTab div in the navigation bar to the trolley div without the shopping cart disappearing until onmouseout which was strangely set only to the shoppingTab in the navigation bar, not the trolley div itself but I liked this odd little quirk. Therefore I would like to replicate this behaviour on to my new site.
Don't worry: I know what you've read up to this point hasn't been enough information to go off, don't worry there is more detailed stuff sitting below above my current code. You'll get what I mean when you scroll further down :).
PROTOTYPE CODE
Here is the prototype on JSFiddle (and it doesn't work onmouseover???) https://jsfiddle.net/Please_Reply/k1k566wp/1/ so just in case here is the raw code which will work if you copy and paste it into a blank HTML file etc.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
.container{
width:960px;
margin:auto;
}
.header{
width:960px;
height:100px;
background-color:#06F;
float:left;
}
#trolley{
width:150px;
height:30px;
background-color:white;
float:right;
border-radius:10px;
color:black;
border:1px solid black;
line-height:30px;
font-family:"Calibri";
cursor: pointer;
}
.shop{
width:960px;
height:700px;
background-color:white;
float:left;
font-family:"Calibri Light";
padding:20px;
}
#shoppingTab{
display:none;
height:400px;
width:400px;
background-color:#CCC;
color:black;
position:relative;
margin-top:1px;
border-radius:10px;
color:black;
border:1px solid black;
padding-left:10px;
float:right;
}
html{
background-color:#00F;
}
.product{
height:200px;
width:150px;
float:left;
border: 1px solid black;
border-radius:10px;
margin-right:20px;
font-size:16px;
text-align:center;
cursor:pointer;
}
.product:hover{
border:1px solid blue;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<span id="name"></span><div id="trolley" onmouseover="tabDisplay('block')" onmouseout="tabDisplay('none')"><center>Shopping Cart <span style='font-family:webdings'>¤</span> <span id="NOI" style="background-color:red; border-radius:360px; color:white; padding-left:5px;padding-right:5px">0</span></center>
<div id="shoppingTab">You have selected <span id="NOI2">0</span> items. Your total is $<span id="totalPrice">0</span><br/><span id="itemsList"></span></div>
</div>
</div>
<div class="shop" style="font-size:28px">Welcome, <span id="name2"></span>.<hr /><br/>Products<br/><hr />
<div class="product" onclick="addToCart('sunglasses', 0, 70)">Pair of sunglasses ($70)<br /><br /><span onclick="change(1)">Click to add to cart</span></div>
<div class="product" onclick="addToCart('shoes', 1, 180)">Pair of shoes ($180)<br /><br /><span onclick="change(3)">Click to add to cart</span></div>
<div class="product" onclick="addToCart('belt', 2, 20)">A belt ($20)<br /><br /><span onclick="change(3)">Click to add to cart</span></div>
</div>
</div>
</body>
</html>
<script>
var customerName = "";
var numberOfItems = 0;
var total = 0;
var items = [];
var stat = []
for(var a = 1; a <= 3; a++){
stat[a] = false;
}
function update(){
document.getElementById("NOI").innerHTML = numberOfItems;
document.getElementById("NOI2").innerHTML = numberOfItems;
document.getElementById("totalPrice").innerHTML = total;
document.getElementById("itemsList").innerHTML = items.join("<br />");
}
function tabDisplay(displayStatus){
shoppingTab.style.display = displayStatus;
}
function addToCart(productName, productID, price){
items[productID] = productName;
total += price;
numberOfItems++;
update();
}
function removeFromCart(productName, productID, price){
items.splice(productID, 1);
total -= price;
if(stat[productID]){
numberOfItems--;
}
update();
}
function change(i){
if(stat[i] == false){
stat[i] = true;
}else{
stat[i] = false;
}
}
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("customer");
if (user != "") {
customerName = getCookie("customer");
document.getElementById("name").innerHTML = customerName;
alert("Welcome again, " + user + ".");
} else {
document.getElementById("name").innerHTML = "please set up an account";
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("customer", user, 30);
document.getElementById("name").innerHTML = user;
}
}
}
function changeCookie(){
var user = getCookie("customer");
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("customer", user, 30);
}
document.getElementById("name").innerHTML = user;
}
checkCookie();
</script>
MY CURRENT CODE
I have a JSFiddle of my current code (Which doesn't work so I copied the code below as well. I think it is because I have pure Javascript in there which it is trying to read as JQuery??? I don't know... anyway if you can't fix the JSFiddle just copy the code that actually works below the JSFiddle link)... https://jsfiddle.net/Please_Reply/9uwj2bed/2/
So basically, in the code below, I need the shoppingCart div to appear when you hover over the shopcartbar div (probably using onmouseover). But in terms of onmouseout, I would like to be able to hover onto the shoppingCart div without it disappearing. I would like the onmouseout to work on both the shopcartbar div and the shoppingCart div just like it somehow does in my prototype???
One other issue when I use onmouseover on the shoppingCart div is that when I hover over any of the .smallProduct divs inside of the shoppingCart div, they seem to trigger onmouseout which is not what I want either, they are part of the shoppingCart div.
<head>
<style>
body{ /* Applies to the <body> tag */
margin:0px; /* Sets the margin on all sides to 0px */
}
.container{ /* The container class */
width:100%; /* This sets the width */
height:100%; /* This sets the height */
background-color:white; /* Sets the background colour */
font-family:"Myriad Pro"; /* Sets the font family */
}
.header{ /* The header class */
width:100%;
background-color:blue;
color:white; /* The sets the colour of the font */
}
div{
display: inline-block; /* Sets the display type */
float:left; /* Sets the float position */
}
#one, #two, #three, #four{
background-color:black;
height:90px;
color:white;
text-align:center;
font-size:25px;
}
#slider{
background-color:blue;
height:10px;
width:100px;
position: absolute; /* Sets the position to a specific type */
left: 0; /* Sets the number of pixels from the left that this object is placed */
bottom:0; /* Sets the number of pixels from the bottom that this object is placed */
}
.inside{
margin-left:30px; /* Specifies the margin from the left side */
margin-right:30px; /* Specifies the margin from the right side */
padding-top:7px; /* Specifies the padding from the top side */
pointer-events:none; /* Specifies the cursor events */
margin-top:25px; /* Specifies the margin from the top side */
}
#shoppingTab{
display:none;
height:670px;
width:400px;
background-color:white;
color:black;
position:relative;
margin-top:-2px;
border-radius:10px;
color:black;
border:1px solid #323232;
padding:10px;
float:right;
z-index:50;
}
.smallProduct{
height:50px;
width:390px;
float:left;
border: 2px solid black;
border-radius:10px;
font-size:16px;
cursor:pointer;
margin-bottom:10px;
overflow:hidden;
}
.smallProduct:hover{
border:2px solid blue;
}
</style>
</head>
<body>
<div class="container"> <!-- This is the container -->
<div class="header"> <!-- This is the header -->
<div style="float:left"> <!-- This is the logo -->
<img src="logo.png" height="120px"/>
</div>
<div style="float:right; font-family:'Myriad Pro'; background-image:url(images/loginsignupbar.png); width:535.1px; height:30px">
<div onmouseover="tabDisplay('block')" id="shopcartbar" style="float:right; font-size:24px; margin-top:-7px">
<img src="images/shoppingCart.png" height="30px"/> Shopping Cart (<span id="numberOfItems">0</span>)
</div>
<div id="shoppingTab" onmouseout="tabDisplay('none')">
Shopping Cart<br />
<div class="smallProduct" style="margin-top:5px" id="thmbproduct0"></div>
<div class="smallProduct" id="thmbproduct1"></div>
<div class="smallProduct" id="thmbproduct2"></div>
<div class="smallProduct" id="thmbproduct3"></div>
<div class="smallProduct" id="thmbproduct4"></div>
<div class="smallProduct" id="thmbproduct5"></div>
<div class="smallProduct" id="thmbproduct6"></div>
<div class="smallProduct" id="thmbproduct7"></div>
<div class="smallProduct" id="thmbproduct8"></div>
Total: $<span id="totalPrice">00</span>.00
</div>
<span id="topnavbar" style="float:right; font-size:24px; margin-top:5.5px">
</span>
</div>
<div style="float:right; clear:right"> <!-- This is the navigation menu -->
<div style="position:relative"> <!-- This is the container of the navigation menu -->
<div id="slider"></div> <!-- This is the slider bar -->
<div id="one" class="item"><div class="inside">Button 1</div></div> <!-- This is just one of the buttons -->
<div id="two" class="item"><div class="inside">Button 2</div></div>
<div id="three" class="item"><div class="inside">Button 3</div></div>
<div id="four" class="item"><div class="inside">Button 4</div></div>
</div>
</div>
</div>
</div>
</body>
</html>
<script>
function tabDisplay(displayStatus){
shoppingTab.style.display = displayStatus;
}
</script>
<script type="text/javascript" src="./jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {
$("#slider").animate({
"left": $('#three').position().left + "px",
"width": $('#three').width() + "px"
}, 0);
$(".item").hover(function() {
$("#slider").stop();
$("#slider").animate({
"left": $(this).position().left + "px",
"width": $(this).width() + "px"
}, 500);
});
$(".item").on("mouseout", function() {
$("#slider").stop();
$("#slider").animate({
"left": $('#three').position().left + "px",
"width": $('#three').width() + "px"
}, 500);
});
});
</script>
Try replacing this section:
function tabDisplay(displayStatus){
shoppingTab.style.display = displayStatus;
}
With this:
$( "#shopcartbar, #shoppingTab" ).mouseenter(function() {
$("#shoppingTab").show();
})
.mouseleave(function() {
$("#shoppingTab").hide();
});

Custom confirmbox, wait for button click in function Javascript

I want to make a confirmbox that returns true or false. If the user clicks OK it has to return true and if the user clicks Cancel or the cross in the upperleft corner it has to return false. But I'm stuck at the point the user clicks the button. I've already tried using callbacks but it could not help me to achieve what I would like to have.
So far I have this:
Fiddle
function SimpleAlert( title, text, cancel)
{
var stylesheet = document.createElement('style');
stylesheet.id="SimpleAlertStylesheet";
stylesheet.innerHTML="#SimpleAlertOverlay { top:0px; bottom:0px; left:0px; right:0px; position:fixed; background:rgba(230,230,230,0.5); height:100%; width:100%; font-family:Sans-serif; } #SimpleAlertLightbox { background:#f5f5f5; border-radius:3px; width:400px; box-shadow: 0px 0px 15px rgba(0,0,0,0.3); } .SimpleAlertTopbar { border-radius:3px; background:#e5e5e5; height:24px; color:#444; line-height:24px; padding:0px 5px; font-weight:bold; font-size:14px; border-bottom:1px solid #DDD } .SimpleAlertCross1 { margin:5px 15px 0px 0px; opacity:0.7; } .SimpleAlertCross2 { margin:5px 15px 0px 0px; opacity:0.5; } .SimpleAlertCross1:hover { opacity:1; } .SimpleAlertTopbar > div { float:left } .SimpleAlertMessagediv { padding:20px 40px; font-size:14px; color:#444; } .SimpleAlertButtondiv { height:26px; line-height:26px; padding:0px 40px 18px 40px; } .SimpleAlertButtondiv button { height:26px; background:#f9f9f9; border:1px solid #CCC; color:#444; float:right; } .SimpleAlertButtondiv button:hover { border:1px solid #AAA; } .SimpleAlertButtondiv button:focus { outline:none; }";
var overlay = document.createElement('div');
overlay.id = 'SimpleAlertOverlay';
var lightbox = document.createElement('div');
lightbox.id = 'SimpleAlertLightbox';
overlay.appendChild(lightbox);
var topbar = document.createElement('div');
topbar.setAttribute("class", "SimpleAlertTopbar");
lightbox.appendChild(topbar);
var crossdiv = document.createElement('div');
topbar.appendChild(crossdiv);
var crossspan = document.createElement('span');
crossdiv.appendChild(crossspan);
var cross = document.createElement('img');
if(cancel)
{
cross.setAttribute("class", "SimpleAlertCross1");
}
else
{
cross.setAttribute("class", "SimpleAlertCross2");
}
cross.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NDBGMDEwRUNCQTQyMTFFMzlBNjZDNzQ4QzkxQTI1QkYiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NDBGMDEwRURCQTQyMTFFMzlBNjZDNzQ4QzkxQTI1QkYiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo0MEYwMTBFQUJBNDIxMUUzOUE2NkM3NDhDOTFBMjVCRiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo0MEYwMTBFQkJBNDIxMUUzOUE2NkM3NDhDOTFBMjVCRiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pp1kTM8AAAFGSURBVHjalJI9S0JRGMd/VwKnbKkQvOpUBqIOOrj4DTTEanKqzSGQvknt9gXiIgp+BScXdZEKB18GockGscHTc7zdazcs8g+/w3l5nvM/L4+hlMJVKnUo7Z2QF06/ZgdCU3ig231zQg03MZm8kLYmHLBdc+GGXs/aJCYSOulJj/lb2uWKft8yVDx+JINXIcD/pJ1PfKxWt0JAYE2pBJWK3c9moVqFYBB33Y6t+lDqHH1ch3YbTBPKZSgUYDaD6RRPjFJ57Xj2bTcYj6HTgXQalktoNPCs28T21p2fWiw2fSfYqw/tOPDsFgpBLme7+v1QLG5zHOrEpmdS320uD1eTL63XIZOxj+1NbBkqGj0W65ddv8MugEhktwIYjaxNyYXDl9I+Cvu/JL0L1/LqlrdWtUzTKXL5QGL69YRnoSXcM5m4Rf4pwABHDba2DxAS7QAAAABJRU5ErkJggg==';
crossspan.appendChild(cross);
var titlediv = document.createElement('div');
titlediv.innerHTML = title;
topbar.appendChild(titlediv);
var messagediv = document.createElement('div');
messagediv.setAttribute("class", "SimpleAlertMessagediv");
messagediv.innerHTML = text;
lightbox.appendChild(messagediv);
var buttondiv = document.createElement('div');
buttondiv.setAttribute("class", "SimpleAlertButtondiv");
lightbox.appendChild(buttondiv);
var okbutton = document.createElement('button');
okbutton.innerHTML="OK";
buttondiv.appendChild(okbutton);
document.body.appendChild(overlay);
document.body.appendChild(stylesheet);
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
function CenterDiv(elementId){
var main = document.getElementById(elementId);
var wi=main.offsetWidth;
var he=main.offsetHeight;
var marginleft = wi / 2;
var margintop = he / 2;
main.style.marginLeft="-" + marginleft;
main.style.marginTop="-" + margintop;
main.style.position="absolute";
main.style.left="50%";
main.style.top="50%"
}
CenterDiv('SimpleAlertLightbox');
if(cancel)
{
var cancelbutton = document.createElement('button');
cancelbutton.innerHTML="Cancel";
cancelbutton.style.marginRight="30px";
buttondiv.appendChild(cancelbutton);
cancelbutton.addEventListener('click', SimpleAlertCancel , false);
}
cross.addEventListener('click', SimpleAlertCancel , false);
okbutton.addEventListener('click', SimpleAlertOK , false);
function SimpleAlertCancel()
{
document.body.removeChild(document.getElementById('SimpleAlertOverlay'));
document.body.removeChild(document.getElementById('SimpleAlertStylesheet'));
}
function SimpleAlertOK()
{
document.body.removeChild(document.getElementById('SimpleAlertOverlay'));
document.body.removeChild(document.getElementById('SimpleAlertStylesheet'));
}
}
What I'm trying to achieve is:
if(SimpleAlert('title', 'text', true))
{
//User clicked OK
}
else
{
//User clicked Cancel
}
I am looking for something like the system functions: alert(), confirm() and prompt(). These functions pause all Javascript and wait until a button has been clicked.
I have browsed throught all the folders of the internet browsers installed on my computer to find the above functions declared but i couldn't find them.
Here is an image of the alertbox for the person that doesn't open the fiddle ;-)
I hope you can help me to get a step closer.
You can't do that with Javascript, as it is asynchronous, the code continues executing even if the window/div is shown.
For managing the actions, execute the code you need on the onclick events on each of the "OK" and "Cancel" buttons

javascript onclick create(element) div viz popup box

I'm trying to make a pop up box, which gets invoked on clicking a button, this is what I've got so far.. http://jsfiddle.net/WGPhG/2/
Here is a fiddle that actually does what you want - http://jsfiddle.net/WGPhG/6/
JS
function popUp(){
var popup = document.createElement('div');
popup.className = 'popup';
popup.id = 'test';
var cancel = document.createElement('div');
cancel.className = 'cancel';
cancel.innerHTML = 'close';
cancel.onclick = function (e) { popup.parentNode.removeChild(popup) };
var message = document.createElement('span');
message.innerHTML = "This is a test message";
popup.appendChild(message);
popup.appendChild(cancel);
document.body.appendChild(popup);
}
NOTES
To set the class on an element you use element.className instead of element.class.
For the onclick event handler on the cancel element, it is better to directly assign the onclick handler with an anonymous function that does what you need as in my example above.
EDIT (More Efficient Way)
This is actually a much better of getting the results that you want because there is no overhead involved with recreating the elements every time the popup is shown. Fiddle - http://jsfiddle.net/WGPhG/7/
CSS
.popup
{
position:absolute;
top:0px;
left:0px;
margin:100px auto;
width:200px;
height:150px;
font-family:verdana;
font-size:13px;
padding:10px;
background-color:rgb(240,240,240);
border:2px solid grey;
z-index:100000000000000000;
display:none
}
.cancel
{
display:relative;
cursor:pointer;
margin:0;
float:right;
height:10px;
width:14px;
padding:0 0 5px 0;
background-color:red;
text-align:center;
font-weight:bold;
font-size:11px;
color:white;
border-radius:3px;
z-index:100000000000000000;
}
HTML
<button onClick="openPopup();">click here</button>
<div id="test" class="popup">
This is a test message
<div class="cancel" onclick="closePopup();"></div>
</div>
JS
function openPopup() {
document.getElementById('test').style.display = 'block';
}
function closePopup() {
document.getElementById('test').style.display = 'none';
}
Try this update on JSFiddle
Changed :
Center page (fixed).
effect (fadein and fadeout)
HTML
<button onClick="openPopup();">click here</button>
<div id="test" class="popup" style="display:none;">
This is a test message
<div class="cancel" onclick="closePopup();"></div>
</div>
CSS
.popup {
position:fixed;
top:0px;
left:0px;
bottom:0px;
right:0px;
margin:auto;
width:200px;
height:150px;
font-family:verdana;
font-size:13px;
padding:10px;
background-color:rgb(240,240,240);
border:2px solid grey;
z-index:100000000000000000;
}
.cancel {
display:relative;
cursor:pointer;
margin:0;
float:right;
height:10px;
width:14px;
padding:0 0 5px 0;
background-color:red;
text-align:center;
font-weight:bold;
font-size:11px;
color:white;
border-radius:3px;
z-index:100000000000000000;
}
.cancel:hover {
background:rgb(255,50,50);
}
JS
function openPopup() {
//document.getElementById('test').style.display = 'block';
$('#test').fadeIn(1000);
}
function closePopup() {
//document.getElementById('test').style.display = 'none';
$('#test').fadeOut(500);
}
Try This
function popUp(){
var popup = document.createElement('div');
popup.className = 'popup';
popup.id = 'test';
var cancel = document.createElement('div');
cancel.className = 'cancel';
cancel.setAttribute('onClick', 'document.getElementById("test").parentNode.removeChild('+popup +');')
popup.innerHTML = "This is a test message";
document.body.appendChild(popup);
popup.appendChild(cancel);
}
I've updated your Fiddle and made it work.
The changed HTML...
<button id="popupButton">click here</button>
Updated JavaScript...
document.onreadystatechange = function () {
function popUp() {
var popup = document.createElement('div');
popup.className = 'popup';
popup.id = 'test';
popup.innerHTML = "This is a test message";
var cancel = document.createElement('div');
cancel.className = 'cancel';
cancel.onclick= function () { popup.destroy(); }
popup.appendChild(cancel);
document.body.appendChild(popup);
}
document.getElementById('popupButton').onclick = popUp;
}​
Did this answer your question or is there anything else?
Update Improved the code and the fiddle. Now open and close works

Categories