In my PhoneGap Eclipse project I am using jQuery for visual effects by referencing jQuery libraries:
<link rel="stylesheet"
href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript"
src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.js"></script>
and I am also making remote domain requests in order to display some information from the remote server.
1: When I make requests to multiple servers, I get an error saying:
DroidGap: TIMEOUT ERROR! - calling webViewClient
I read that I must alter my Phonegaps whitelist by doing:
<phonegap>
<access origin="\*\" />
</phonegap>
Source: GitHub call-back
But I get some error, so I have decided to approach same results from the different ways:
2: <script type="text/javascript" src="file:///android_asset/js/jquery.js"></script>
<script type="text/javascript" src="../js/jquery.js"></script>
Why? - because i would like to avoid getting errors with multiple-domain requests
In these cases I get an error
SyntaxError: Parse error at file:///... in logcat
I have no idea why this is happening, because the specified file location supposed to be right in both cases.
So my questions are:
Why I cannot include .js file in this way?
Which solution I should continue trying to approach (1 or 2)?
<html>
<head>
<title></title>
<script src="phonegap-1.3.0.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.0.css" />
<script type="text/javascript" src="jquery.mobile-1.0.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<!--
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="lib/touch/resources/css/sencha-touch.css" type="text/css">
<script type="text/javascript" src="lib/touch/sencha-touch.js"></script>
<!-- <script type="text/javascript" src="lib/touch/index.js"></script> -->
<script>
var alreadyrunflag = 0 //flag to indicate whether target function has already been run
var url = "http://www.norwegian.no/";
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var year = currentTime.getFullYear();
//on page loaded
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", function() {
//alreadyrunflag = 1;
initGet(url);
}, false)
else if (document.all && !window.opera) {
//page load error?
}
function applyChangeEvent() {
//on selection changed
var selectDepart = document.getElementById("depart");
var selectArrive = document.getElementById("arrive");
selectDepart.onchange = function() { //run some code when "onchange" event fires
if (document.getElementsByTagName("select")[1].options[document
.getElementsByTagName("select")[1].options.selectedIndex].value != ""
&& document.getElementsByTagName("select")[0].options[document
.getElementsByTagName("select")[0].options.selectedIndex].value != "") {
for ( var monthsCount = 1; monthsCount < 13; monthsCount++) {
//alert(monthsCount);
get("http://www.norwegian.no/fly/lavpris/", monthsCount);
}
}
}
selectArrive.onchange = function() { //run some code when "onchange" event fires
if (document.getElementsByTagName("select")[1].options[document
.getElementsByTagName("select")[1].options.selectedIndex].value != ""
&& document.getElementsByTagName("select")[0].options[document
.getElementsByTagName("select")[0].options.selectedIndex].value != "") {
for ( var monthsCount = 1; monthsCount < 13; monthsCount++) {
//alert(monthsCount);
get("http://www.norwegian.no/fly/lavpris/", monthsCount);
}
}
}
}
function initGet(url) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
//request.responseText
getObjs(request.responseText);
}
}
}
request.send();
}
function get(url, month) {
//alert(month);
url += "?D_City="
+ document.getElementsByTagName("select")[0].options[document
.getElementsByTagName("select")[0].options.selectedIndex].value;
url += "&A_City="
+ document.getElementsByTagName("select")[1].options[document
.getElementsByTagName("select")[1].options.selectedIndex].value;
url += "&TripType=1";
url += "&D_Day=1";
url += "&D_Month=" + getMonth(month);
/* url += "&R_Day=1";
url += "&R_Month=201201"; */
url += "&AdultCount=1";
url += "&ChildCount=0";
url += "&InfantCount=0";
//alert(url);
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
//request.responseText
parse(request.responseText, month);
}
}
}
request.send();
}
function getMonth(month) {
//alert(month.toString.length + " | " + month);
if (month.toString().length == 1) {
var tempMonth = "0" + month.toString();
//alert(tempMonth);
return year.toString() + tempMonth;
} else
return year.toString() + month;
}
function getSimpleMonth() {
return month;
}
function getObjs(mainPageHtml) {
var mainDoc = (new DOMParser()).parseFromString(mainPageHtml,
"application/xhtml+xml");
var select = mainDoc.getElementsByTagName("select")[1];
var options = select.getElementsByTagName("option");
var citiesArray = [];
for ( var i = 0; i < options.length; i++) {
cityObj = new Object();
cityObj.name = options[i].text;
cityObj.value = options[i].value;
citiesArray.push(cityObj);
}
for ( var city = 0; city < citiesArray.length; city++) {
document.getElementById("depart").innerHTML += "<option value='"+citiesArray[city].value+"'>"
+ citiesArray[city].name + "</option>";
document.getElementById("arrive").innerHTML += "<option value='"+citiesArray[city].value+"'>"
+ citiesArray[city].name + "</option>";
}
applyChangeEvent();
}
function parse(html, id) {
var pricesArray = [];
//alert(id);
var resultDoc = (new DOMParser()).parseFromString(html,
"application/xhtml+xml");
var divs = resultDoc.getElementsByTagName("table");
for ( var div = 0; div < divs.length; div++) {
if (divs[div].className == "fareCalendarTable") {
//alert("found!");
// TODO: find out how many to open!!
document.getElementById(id).style.display = "block";
document.getElementById("nav_").style.display = "block";
var table = resultDoc.getElementsByTagName("table")[div];
var divs = table.getElementsByTagName("div");
//var tbodyTrs = tbody.getElementsByTagName("tr");
//alert(document.getElementById("month-one").innerHTML);
for ( var price = 0; price < divs.length; price++) {
if (divs[price].title != "") {
/* document.getElementById("month-one-results").innerHTML += divs[price].id
.replace("OutboundFareCal", "")
+ " : " + divs[price].title + "<br>"; */
priceObj = new Object();
priceObj.date = divs[price].id.replace(
"OutboundFareCal", "");
priceObj.price = divs[price].title.replace(" NOK", "");
priceObj.price.replace(/\s/g, '');
pricesArray.push(priceObj);
}
}
/* pricesArray.sort(function sortNumber(a, b) {
return parseInt(b) - parseInt(a);
}); */
for ( var priceUnit = 0; priceUnit < pricesArray.length; priceUnit++) {
document.getElementById("month-results-" + id).innerHTML += "<table><tr><td>"
+ pricesArray[priceUnit].date
+ "</td><td>"
+ pricesArray[priceUnit].price
+ "</td></tr></table>";
}
}
document.getElementById("depart").disabled = "disabled";
document.getElementById("arrive").disabled = "disabled";
}
// document.getElementById("results").innerHTML = bodybox.item(0).innerHTML;
//holy grail!
var month = document.getElementById("month-" + id);
var spans = month.getElementsByTagName("span");
for ( var span = 0; span < spans.length; span++) {
if (spans[span].className == "ui-btn-text") {
spans[span].innerHTML += "<p>" + getCheapest(pricesArray)
+ "</p>";
}
}
}
function getCheapest(pricesArray) {
pricesArray.sort(sort);
return pricesArray[1].price;
}
function sort(a, b) {
if (a.price < b.price)
return -1;
if (a.price > b.price)
return 1;
return 0;
}
function restart() {
window.location.reload();
return false;
document.getElementById("depart").removeAttribute("disabled");
document.getElementById("arrive").removeAttribute("disabled");
}
</script>
<style>
body {
display: block;
padding: 20px;
color: #3D3C2F;
font-family: Arial, Sans-Serif, Helvetica;
font-size: 12px;
font-weight: normal;
}
div#content {
margin-left: auto;
margin-right: auto;
background: #fff;
height: 100%;
-webkit-border-bottom-left-radius: 8px;
-webkit-border-bottom-right-radius: 8px;
display: block;
color: #3D3C2F;
font-family: Arial, Sans-Serif, Helvetica;
font-size: 12px;
font-weight: normal;
background-image:
url(http://www.norwegian.no/Global/backgrounds/background_no.gif);
background-repeat: repeat-x;
background-repeat-x: repeat;
background-repeat-y: no-repeat;
background-position-x: 0%;
background-position-y: 0%;
width: 100%;
padding-top: 20px;
padding-bottom: 30px;
}
div#navigation {
margin-left: auto;
margin-right: auto;
padding: 20px;
position: block;
width: 80%;
background: #CCCC00;
-webkit-border-radius: 8px;
}
select {
position: block;
width: 100%;
text-color: #000;
overflow: hidden;
}
</style>
</head>
<body>
<div id="nav_" data-role="header" data-position="inline" data-theme="e"
style="display: none;">
<a href="#" data-icon="back" data-theme="c"
onClick="window.location.reload();return false;">Start</a>
<h1>Ticket Prices</h1>
</div>
<div id="content">
<div id="navigation">
Fra/From: <select id="depart">
</select> Til/To: <select id="arrive">
</select>
</div>
<div data-role="collapsible" id="1"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-1">January</h3>
<p id="month-results-1"></p>
</div>
<div data-role="collapsible" id="2"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-2">February</h3>
<p id="month-results-2"></p>
</div>
<div data-role="collapsible" id="3"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-3">March</h3>
<p id="month-results-3"></p>
</div>
<div data-role="collapsible" id="4"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-4">April</h3>
<p id="month-results-4"></p>
</div>
<div data-role="collapsible" id="5"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-5">May</h3>
<p id="month-results-5"></p>
</div>
<div data-role="collapsible" id="6"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-6">June</h3>
<p id="month-results-6"></p>
</div>
<div data-role="collapsible" id="7"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-7">July</h3>
<p id="month-results-7"></p>
</div>
<div data-role="collapsible" id="8"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-8">August</h3>
<p id="month-results-8"></p>
</div>
<div data-role="collapsible" id="9"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-9">September</h3>
<p id="month-results-9"></p>
</div>
<div data-role="collapsible" id="10"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-10">October</h3>
<p id="month-results-10"></p>
</div>
<div data-role="collapsible" id="11"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-11">November</h3>
<p id="month-results-11"></p>
</div>
<div data-role="collapsible" id="12"
style="display: none; background: #fff; width: 97%; margin-left: auto; margin-right: auto;">
<h3 id="month-12">December</h3>
<p id="month-results-12"></p>
</div>
</div>
<!-- <div id="results"></div> -->
</body>
</html>
If your directory structure is assets/www/js/jquery.js use :
<script type="text/javascript" src="js/jquery.js"></script>
Related
![Text](https://stackoverfl
var obj = {
count: 1
}
function elementSet()
{
if(obj.count=1){
document.getElementById("text").textContent = "graa";}
if(obj.count=2){
document.getElementById("text").textContent = "graa";}
if(obj.count=3){
document.getElementById("text").textContent = "graa";}
}
function back()
{
if(obj.count>1)
{
obj.count = obj.count -1;
document.getElementById("back").style.display = "block";
document.getElementById("page_num").textContent = obj.count;
}
}
function forth()
{
if(obj.count<3){
obj.count = obj.count +1;
document.getElementById("page_num").textContent = obj.count;
document.getElementById("forth").style.display = "block";
if (obj.count>3){
document.getElementById("forth").style.display = "none";}
}
}
.colx1 {
color: #e1992e;
/* height: 3px; */
font-size: 2.1ch;
margin-right: 80%;
inline-size: auto;
border-color: #e1992e;
border-radius: 11ch;
}
.colx2 {
color: #e1992e;
font-size: 2.1ch;
inline-size: auto;
margin-top: -3%;
margin-left: 80%;
border-color: #e1992e;
border-radius: 11ch;
}
.colabount
{
width: 170px;
}
.row {
display: inline;
}
.body
{
text-align: center;
max-height: 100%;
}
.button {
border-color: #e1992e;
}
.page_num
{
color: black;
size: 13ch;
text-align: center;
}
.text
{
color: blanchedalmond;
size: 12ch;
}
<!DOCTYPE html>
<html>
<head>
<title>films</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body class="body">
<div class="container external internal" id="content">
<h2 id="text" class="text" type="textContent"> its the f</h2>
<div class="row">
<button class="colx1" id="back" type="button" onclick="back(),elementSet()"><b>back</d></button>
<button class="colx2" id="forth" type="button" onclick="forth(),elementSet()"><b>forth</d></button>
</div>
<div class="page_num"><b id ="page_num">1</b></div>
</div>
</body>
</html>
ow.com/image.jpg)
i tried to create external obj that contain count its working.
the page content will change acording to the count number.
the proble starts when im calling 'elementSet' = {checking abount obj.count and
changing the page acordingly}
THE PROBLEM : when elementSet runs back() and forth() not working anymore!
your mistake is that:
in java script = is assignment. for example: let a = 0;
we assignment 0 to a. now a is 0.
and we have == and ===. these are use for comparison in logics and Condition. for example:
let a = 0;
a == 0 && console.log("yes");
there are some different between == and ===. you can read that in a link!
I have button that creates block. When i click on the button, pops up a window with the settings of this block. And there i have settings with position of this block. When i create block and give theme position right, all is ok. But when add another block and give position left, left is givven to first and secont block, but not to second. Why?
function showBlockWindow() {
var modal = $(".modal-block-container");
if (modal.css('display', "none")) {
modal.css('display', "grid");
} else {
modal.css('display', "none");
}
}
function addBlock() {
var widthInp = $("#width").val();
var heightInp = $("#height").val();
var align = $(".form-align-block").val();
var background = "background-color:";
var backgroundColor = "black";
var closeTag = ";";
var width = "width:";
var percent = "%";
var px = "px";
var onclick = 'onclick="editBlock(this)"';
var margin = "margin:";
var height = "height:";
var block = ("<div class='block-" + align + " preview-block' " + onclick + " style=" + background + backgroundColor + closeTag + width +
widthInp + percent + closeTag + height + heightInp + px + "></div>");
$(".preview").append(block);
if (align == "left" || "right") {
$(".preview .preview-block").css("margin-" + align + "", "auto");
} else if (align == "center") {
$(".preview .preview-block").css("margin", "auto");
}
}
function editBlock(elem) {
$('.preview-block').removeClass('preview-block');
$(elem).addClass('preview-block');
$('.preview-edit-block').show();
}
.addBlock {
font-size: 1.2em;
list-style: none;
transition: 0.1s;
padding: 5px;
}
.modal-block-container {
justify-content: center;
right: 0;
left: 0;
position: fixed;
top: 15%;
display: none;
}
.input-block {
padding-bottom: 2%;
padding-top: 1%;
}
#width,
#height {
padding: 4px;
font-family: 'Scada', sans-serif;
}
.edit-block-modal {
padding-bottom: 2%;
}
.preview-edit-block {
background: #272822;
width: 20%;
height: 100vh;
float: right;
color: white;
font-family: 'Scada', sans-serif;
padding: 20px;
display: none;
position: fixed;
z-index: 9;
top: 0;
right: 0;
overflow: scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="add-block">
<li class="addBlock" onclick="showBlockWindow()">Пустой блок</li>
</ul>
<div class="modal-block-container">
<div class="modal-insert-txt">
<div class="header-modal">
<h2>Вставить пустой блок</h2>
</div>
<hr>
<div class="edit-block-modal">
<span>Ширина</span><br>
<div class="input-block">
<input type="text" id="width"> %
</div>
<span>Длина</span><br>
<div class="input-block">
<input type="text" id="height"> px
</div>
<span>Выравнивание блока</span>
<div class="form-group">
<select class="form-align-block">
<option value="left">Слева</option>
<option value="center">По центру</option>
<option value="right">Справа</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn-insert-txt" onclick="addBlock()">Вставить текст</button>
</div>
</div>
</div>
<div class="preview">
</div>
<div class="preview-edit-block">
</div>
Help me please
I would like to know if there's any way to add images to the arrays of my Slot machine? Right now i've just been able to add numbers in the array.
So far i got this, i know there's only one choice in my array, it's on purpose:
var arr = ["#7.png"];
// var arr = [5];
var credits = 10;
function freezeCheck() {
if (document.getElementById("hold1").checked == true || document.getElementById("hold2").checked == true || document.getElementById("hold3").checked == true) {
// if any is checked, freeze hold buttons.
document.getElementById("hold1").checked = false;
document.getElementById("hold2").checked = false;
document.getElementById("hold3").checked = false;
document.getElementById("hold1").disabled = true;
document.getElementById("hold2").disabled = true;
document.getElementById("hold3").disabled = true;
} else if (document.getElementById("hold1").disabled == true) {
// if any diabled, enable (unfreeze) all hold buttons.
document.getElementById("hold1").disabled = false;
document.getElementById("hold2").disabled = false;
document.getElementById("hold3").disabled = false;
document.getElementById("reel1").classList.remove('hold');
document.getElementById("reel2").classList.remove('hold');
document.getElementById("reel3").classList.remove('hold');
}
};
function getNumbers() {
if(document.getElementById("hold1").checked == false){
document.getElementById("reel1").innerHTML = arr[Math.floor(Math.random() * arr.length)];
} if (document.getElementById("hold2").checked == false){
document.getElementById("reel2").innerHTML = arr[Math.floor(Math.random() * arr.length)];
} if (document.getElementById("hold3").checked == false){
document.getElementById("reel3").innerHTML = arr[Math.floor(Math.random() * arr.length)];
}
updateScore();
insertCoins();
};
function calculateScore() {
document.getElementById('credits').innerHTML = credits;
}
// Win, three alike.
function updateScore() {
if(document.getElementById("reel1").textContent == document.getElementById("reel2").textContent && document.getElementById("reel1").textContent == document.getElementById("reel3").textContent){
credits += document.getElementById("reel1").textContent * 10;
} else if("reel1" != "reel2"){
credits -= 2;
}
};
function insertCoins() {
if (credits <1){
document.getElementById("spin").disabled = true;
}
};
function freezeReel(num) {
if (document.getElementById('hold'+num).checked == true) {
// Unfreeze reel
document.getElementById("hold"+num).checked = false;
document.getElementById("reel"+num).classList.remove('hold');
} else {
// Freeze reel:
document.getElementById("hold"+num).checked = true;
document.getElementById("reel"+num).classList.add('hold');
}
}
* {
margin: 0;
padding: 0;
}
.marginauto {
margin: 0 auto;
}
.button-wrapper {
text-align: center;
margin-top: 15%;
}
.hold-wrapper {
text-align: center;
margin: 10px;
font-size: 48px;
}
.holdbutton {
width: 140px;
height: 200px;
visibility: hidden;
}
.credits {
width: 250px;
height: 100px;
margin: 0 auto;
text-align: center;
}
.reel-wrapper {
width: 1280px;
text-align: center;
margin-top: 10px;
background-color: #ffffff;
}
.button {
background-color: white;
}
.reels {
background-color: #ffffff;
display: inline-block;
font-size: 48px;
text-align: center;
width: 150px;
height: 200px;
border: 1px solid black;
border-radius: 2px;
}
.reels.hold {
border-color: blue;
background: #ccc;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> </title>
</head>
<body>
<header></header>
<div class="button-wrapper">
<input id="spin" type="button" onClick="getNumbers(); freezeCheck(); calculateScore();" value="Spin" />
</div>
<div class="reel-wrapper marginauto">
<div id="reel1" onClick="freezeReel(1);" class="reels"></div>
<div id="reel2" onClick="freezeReel(2);" class="reels"></div>
<div id="reel3" onClick="freezeReel(3);" class="reels"></div>
</div>
<div class="hold-wrapper">
<input id="hold1" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold2" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold3" type="checkbox" value="Hold" class="holdbutton" />
</div>
<div class="credits">Your Credits: <span id="credits"></span></div>
<script src="script.js"></script>
</body>
</html>
You should use the backgroundImage javascript property and provide value with a source from the array arr.
Refer code:
var arr = ['image1.png', 'image2.png', 'image3.png'];
var credits = 10;
function freezeCheck() {
if (document.getElementById("hold1").checked == true || document.getElementById("hold2").checked == true || document.getElementById("hold3").checked == true) {
// if any is checked, freeze hold buttons.
document.getElementById("hold1").checked = false;
document.getElementById("hold2").checked = false;
document.getElementById("hold3").checked = false;
document.getElementById("hold1").disabled = true;
document.getElementById("hold2").disabled = true;
document.getElementById("hold3").disabled = true;
} else if (document.getElementById("hold1").disabled == true) {
// if any diabled, enable (unfreeze) all hold buttons.
document.getElementById("hold1").disabled = false;
document.getElementById("hold2").disabled = false;
document.getElementById("hold3").disabled = false;
document.getElementById("reel1").classList.remove('hold');
document.getElementById("reel2").classList.remove('hold');
document.getElementById("reel3").classList.remove('hold');
}
};
function getNumbers() {
if(document.getElementById("hold1").checked == false){
document.getElementById("reel1").backgroundImage = "url(" + arr[0] + ")";
} if (document.getElementById("hold2").checked == false){
document.getElementById("reel2").backgroundImage = "url(" + arr[1] + ")";
} if (document.getElementById("hold3").checked == false){
document.getElementById("reel3").backgroundImage = "url(" + arr[2] + ")";
}
updateScore();
insertCoins();
};
function calculateScore() {
document.getElementById('credits').innerHTML = credits;
}
// Win, three alike.
function updateScore() {
if(document.getElementById("reel1").textContent == document.getElementById("reel2").textContent && document.getElementById("reel1").textContent == document.getElementById("reel3").textContent){
credits += document.getElementById("reel1").textContent * 10;
} else if("reel1" != "reel2"){
credits -= 2;
}
};
function insertCoins() {
if (credits <1){
document.getElementById("spin").disabled = true;
}
};
function freezeReel(num) {
if (document.getElementById('hold'+num).checked == true) {
// Unfreeze reel
document.getElementById("hold"+num).checked = false;
document.getElementById("reel"+num).classList.remove('hold');
} else {
// Freeze reel:
document.getElementById("hold"+num).checked = true;
document.getElementById("reel"+num).classList.add('hold');
}
}
* {
margin: 0;
padding: 0;
}
.marginauto {
margin: 0 auto;
}
.button-wrapper {
text-align: center;
margin-top: 15%;
}
.hold-wrapper {
text-align: center;
margin: 10px;
font-size: 48px;
}
.holdbutton {
width: 140px;
height: 200px;
visibility: hidden;
}
.credits {
width: 250px;
height: 100px;
margin: 0 auto;
text-align: center;
}
.reel-wrapper {
width: 1280px;
text-align: center;
margin-top: 10px;
background-color: #ffffff;
}
.button {
background-color: white;
}
.reels {
background-color: #ffffff;
display: inline-block;
font-size: 48px;
text-align: center;
width: 150px;
height: 200px;
border: 1px solid black;
border-radius: 2px;
}
.reels.hold {
border-color: blue;
background: #ccc;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> </title>
</head>
<body>
<header></header>
<div class="button-wrapper">
<input id="spin" type="button" onClick="getNumbers(); freezeCheck(); calculateScore();" value="Spin" />
</div>
<div class="reel-wrapper marginauto">
<div id="reel1" onClick="freezeReel(1);" class="reels"></div>
<div id="reel2" onClick="freezeReel(2);" class="reels"></div>
<div id="reel3" onClick="freezeReel(3);" class="reels"></div>
</div>
<div class="hold-wrapper">
<input id="hold1" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold2" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold3" type="checkbox" value="Hold" class="holdbutton" />
</div>
<div class="credits">Your Credits: <span id="credits"></span></div>
<script src="script.js"></script>
</body>
</html>
innerHTML stands for standard font in your page and it will only shows text. Since in your array, the value of it is #7.png and it will only display #7.png.
Adding the following code will create img tag in your html code with the images being random.
var elem = document.createElement("img");
elem.setAttribute("src", arr[Math.floor(Math.random() * arr.length)]);
elem.setAttribute("alt", "Slotimg");
document.getElementById("reel1").appendChild(elem);
However if you can create a default image, i would suggest you just add a Img tag in your div, and just change the src attribute by src code, it is going to be much easier and effiecnt
I have this calculator that I'd like for the results to auto update after the the user adds input.
I've tried the .keyup thing, but I don't understand it.
I'm kinda new to javascript.
Here's my codepen for the project.
http://codepen.io/Tristangre97/pen/zNvQON?editors=0010
HTML
<div class="card">
<div class="title">Input</div>
<br>
<div id="metalSpan"><input class="whiteinput" id="numMetal" type="number">
<div class="floater">Metal Quantity</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan"><input class="whiteinput" id="numForge" type=
"number">
<div class="floater">Forge Quantity</div></div>
<br>
<input checked id="rb1" name="fuel" type="radio" value="spark"> <label for=
"rb1">Sparkpowder</label> <input id="rb2" name="fuel" type="radio" value=
"wood"> <label for="rb2">Wood</label><br>
<br>
<button class="actionButton" id="submit" type="button">Calculate</button></div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div>
<br>
<div id="result"><span id="spreadMetal"></span> metal <span class=
"plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class=
"plural"></span> forge <span id="allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br></div>
</div>
</div>
JS
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("#submit").click(function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == '') {
$("#metalAlert").html("Please enter a value");
}
else if (forges == 0 || forges == '') {
$("#metalAlert").html('');
$("#forgeAlert").html("Please enter a value");
}
else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
}
else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
}
else {
$(".plural").html("in the");
}
$("#forgeAlert").html('');
if (metals % 2 == 0) {}
else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(((spread / 2) * 20) / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
}
else {
$("#allSpark").html(String(''));
}
$("#timeSpark").html(String((isWood) ? (sparks / 2) : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html((isWood) ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
To run the function whenever something is inputted in the field, try the
$("input").on('input', function() { .. });
var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
$("#result").hide();
$("#alert").hide();
$("input").on('input', function() {
metals = $("#numMetal").val();
forges = $("#numForge").val();
if (metals == 0 || metals == "") {
$("#metalAlert").html("Please enter a value");
} else if (forges == 0 || forges == "") {
$("#metalAlert").html("");
$("#forgeAlert").html("Please enter a value");
} else {
if ($("input[name=fuel]:checked").val() == "wood") {
isWood = true;
} else {
isWood = false;
}
if (forges > 1) {
$(".plural").html("per");
} else {
$(".plural").html("in the");
}
$("#forgeAlert").html("");
if (metals % 2 == 0) {
} else {
metals = metals - 1;
$("#alert").show();
}
ingots = metals / 2;
spread = Math.floor(metals / forges);
sparks = Math.ceil(spread / 2 * 20 / 60);
if (isWood) {
sparks = sparks * 2;
}
tSpark = sparks * forges;
if (forges > 1) {
$("#allSpark").html(String("(" + tSpark + " total)"));
} else {
$("#allSpark").html(String(""));
}
$("#timeSpark").html(String(isWood ? sparks / 2 : sparks));
$("#spreadMetal").html(String(spread));
$("#spreadSpark").html(String(sparks));
$("#fuelType").html(isWood ? "wood" : "sparkpowder");
$("#result").show();
}
});
});
body {
background-color:#316b6f;
font-family:Helvetica,sans-serif;
font-size:16px;
}
.whiteinput {
outline: none;
border-width: 0px;
margin: 0;
padding: .5em .6em;
border-radius: 2px;
font-size: 1em;
color: #316b6f;
}
.actionButton {
background-color: #316B6F;
color: #fff;
padding: .5em .6em;
border-radius: 3px;
border-width: 0px;
font-size: 1em;
cursor: pointer;
text-decoration: none;
-webkit-transition: all 250ms;
transition: all 250ms;
}
.actionButton:hover {
color: #fff;
}
.actionButton:active {
background: #BBFF77;
color: #316B6F;
-webkit-transition: all 550ms;
transition: all 550ms;
}
.card {
position: relative;
background: #4E8083;
color:#FFFFFF;
border-radius:3px;
padding:1.5em;
margin-bottom: 3px;
}
.title {
background: #76B167;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.title2 {
background: #2F3A54;
padding: 3px;
border-radius: 3px 0px 0px 0px;
position: absolute;
left: 0;
top: 0;
margin-bottom: 5px;
}
.floater {
padding: 3px;
}
.radiobtn {
background: red;
border-radius: 2px;
}
input[type=radio] + label:before {
content: "";
display: inline-block;
width: 20px;
height: 20px;
vertical-align:middle;
margin-right: 8px;
background-color: #aaa;
margin-bottom: 6px;
border-radius: 2px;
-webkit-transition: all 450ms;
transition: all 450ms;
}
input[type=radio], input[type=checkbox] {
display:none;
}
input[type=radio]:checked + label:before {
content: "\2022"; /* Bullet */
color:white;
background-color: #fff;
font-size:1.8em;
text-align:center;
line-height:14px;
margin-right: 8px;
}
input[type=checkbox]:checked + label:before {
content:"\2714";
color:white;
background-color: #fff;
text-align:center;
line-height:15px;
}
*:focus {
outline: none;
}
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="card">
<div class="title">Input</div><br>
<div id="metalSpan">
<input class="whiteinput" id="numMetal" type="number">
<div class="floater">
Metal Quantity
</div>
<div id="metalAlert">
</div>
</div>
<br>
<div id="forgeSpan">
<input class="whiteinput" id="numForge" type="number">
<div class="floater">
Forge Quantity
</div>
</div>
<br>
<input type="radio" id="rb1" name="fuel" value="spark" checked>
<label for="rb1">Sparkpowder</label>
<input type="radio" id="rb2" name="fuel" value="wood">
<label for="rb2">Wood</label><br><br>
<button class="actionButton" id="submit"
type="button">Calculate</button>
</div>
<div id="forgeAlert">
</div>
<div id="radioSpan">
<div class="floater">
</div>
<div class="card">
<div class="title2">Results</div><br>
<div id="result">
<span id="spreadMetal"></span> metal <span class="plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class="plural"></span> forge <span id=
"allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br>
</div>
</div>
</div>
Codepen
It is triggering your errors because that is part of your function.
More info regarding the input method.
Look, you have two options:
Put all your algorithm of submit click into a function and call him into two binds: the submit click and input change (on('change')) or just remove your calculate button and rely the calculation into onchange of the inputs: each change of checks or inputs will trigger the calculation of metals. The second approach it's more interesting for me and removes the necessity to the user clicks to calculate (he already clicked into inputs and checks). Obviously you can add a filter to only allow to calculation function run after a certain minimum number of data filled, it's a good idea to avoid poor results resulted by lack of data.
In order to auto update calculation, we have to listen to users input on input elements. The easiest approach with minimum changes to existing code is to add input events and emit click on the button:
$("#numMetal, #numForge").on('input', function(){
$("#submit").click()
})
Better approach is to move calculation logic to separate function and call it on desirable events:
$("#numMetal, #numForge").on('input', function(){
calculate()
})
$("#submit").click(function(){
calculate()
})
This will keep the code structured and easier to follow.
Try this:
$( "#numMetal, #numForge" ).keyup(function(event) {
console.log('a key has been pressed');
// add code to handle inputs here
});
What happens here is that an event listener - the key up event - is bound to the two inputs you have on your page. When that happens the code inside will be run.
As suggested in other comments it would be a good idea to call a separate method with all the input processing code you have in the submit call, this way you will avoid code duplication.
You will also want to bind events to the checkboxs. This can be achieved with this:
$( "input[name=fuel]" ).on('change',function() {
console.log('checkbox change');
// call processing method here
});
This question already has answers here:
How to move an element into another element
(16 answers)
Closed 7 years ago.
I am new at JavaScript. I am trying to make Snakes and Ladders game with native JavaScript code as much as possible. My problem is that I can not move players from their initial position according to the random number generated when pressing on dice image. Can anyone help me on how to move players?
var gameBoard = {
createBoard: function(dimension, mount, intialPosition) {
var mount = document.querySelector(mount);
if (!dimension || isNaN(dimension) || !parseInt(dimension, 10)) {
return false;
} else {
dimension = typeof dimension === 'string' ? parseInt(dimension, 10) : dimension;
var table = document.createElement('table'),
row = document.createElement('tr'),
cell = document.createElement('td'),
rowClone,
cellClone;
var output;
for (var r = 0; r < dimension; r++) {
rowClone = row.cloneNode(true);
table.appendChild(rowClone);
for (var c = 0; c < dimension; c++) {
cellClone = cell.cloneNode(true);
rowClone.appendChild(cellClone);
}
}
mount.appendChild(table);
output = gameBoard.enumerateBoard(table, intialPosition);
}
return output;
},
enumerateBoard: function(board) {
var rows = board.getElementsByTagName('tr'),
text = document.createTextNode(''),
rowCounter = 1,
size = rows.length,
cells,
cellsLength,
cellNumber,
odd = false,
control = 0;
for (var r = size - 1; r >= 0; r--) {
cells = rows[r].getElementsByTagName('td');
cellsLength = cells.length;
rows[r].className = r % 2 == 0 ? 'even' : 'odd';
odd = ++control % 2 == 0 ? true : false;
size = rows.length;
for (var i = 0; i < cellsLength; i++) {
if (odd == true) {
cellNumber = --size + rowCounter - i;
} else {
cellNumber = rowCounter;
}
cells[i].className = i % 2 == 0 ? 'even' : 'odd';
cells[i].id = cellNumber;
cells[i].appendChild(text.cloneNode());
cells[i].firstChild.nodeValue = cellNumber;
rowCounter++;
}
}
var lastRow = rows[0].getElementsByTagName('td');
lastRow[0].id = 'lastCell';
var firstRow = rows[9].getElementsByTagName('td');
firstRow[0].id = 'firstCell';
intialPosition();
return gameBoard;
}
};
window.onload = (function(e) {
gameBoard.createBoard(10, "#grid", intialPosition);
});
var face1 = new Image()
face1.src = "d1.gif"
var face2 = new Image()
face2.src = "d2.gif"
var face3 = new Image()
face3.src = "d3.gif"
var face4 = new Image()
face4.src = "d4.gif"
var face5 = new Image()
face5.src = "d5.gif"
var face6 = new Image()
face6.src = "d6.gif"
function rollDice() {
var randomdice = Math.floor(Math.random() * 6) + 1;
document.images["mydice"].src = eval("face" + randomdice + ".src")
if (randomdice == 6) {
alert('Congratulations! You got 6! Roll the dice again');
}
return randomdice;
}
function intialPosition() {
$("#firstCell").append($("#player1"));
$("#firstCell").append($("#player2"));
}
/*body {
background-image: url('snakesandladder2.png');
background-repeat: no-repeat;
background-size: 100%;
background-color: #4f96cb;
}*/
#game {
width: 80%;
margin-left: auto;
margin-right: auto;
display: table;
}
#gameBoardSection {
border: 3px inset #0FF;
border-radius: 10px;
width: 65%;
display: table-cell;
}
table {
width: 100%;
}
td {
border-radius: 10px;
width: 60px;
height: 60px;
line-height: normal;
vertical-align: bottom;
text-align: left;
border: 0px solid #FFFFFF;
position: relative;
}
table tr:nth-child(odd) td:nth-child(even),
table tr:nth-child(even) td:nth-child(odd) {
background-color: PowderBlue;
}
table tr:nth-child(even) td:nth-child(even),
table tr:nth-child(odd) td:nth-child(odd) {
background-color: SkyBlue;
}
#lastCell {
background-image: url('rotstar2_e0.gif');
background-repeat: no-repeat;
background-size: 100%;
}
#ladder {
position: absolute;
top: 300px;
left: 470px;
-webkit-transform: rotate(30deg);
z-index: 1;
opacity: 0.7;
}
#bigSnake {
position: absolute;
top: 20px;
left: 200px;
opacity: 0.7;
z-index: 1;
}
#diceAndPlayerSection {
background-color: lightpink;
border: 1px;
border-style: solid;
display: table-cell;
border-radius: 10px;
border: 3px inset #0FF;
width: 35%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link href="StyleSheet1.css" rel="stylesheet" />
<script src="jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="game">
<div id="gameBoardSection">
<div id="grid"></div>
<div id="ladder">
<img src="oie_eRDOY2iqd5oQ.gif" />
</div>
<div id="bigSnake">
<img src="oie_485727sRN4KKBG.png" />
</div>
<div id="player1" style="position:absolute; top:10px; left:10px;">
<img src="humanPiece.png" />
</div>
<div id="player2" style="position:absolute; top:15px; left:5px;">
<img src="computerPiece.png" />
</div>
</div>
<div id="diceAndPlayerSection">
<div id="reset">
<button type="button" name="reset">New Game</button>
</div>
<div>
<button type="button" name="reset">Reset</button>
</div>
<div>
<button type="button" name="addPlayer">Add Player</button>
</div>
<div id="diceSection">
<img src="d1.gif" name="mydice" onclick="rollDice()" style="background-color: white;">
<!--<h2 id="status" style="clear:left;"></h2>-->
</div>
</div>
</div>
<script src="JavaScript1.js"></script>
</body>
</html>
I fell miserable about not being able to finish the game. I really need help. Thanks in advance.
Well, first of all this question has been already asked and answered on SO and table cells are just the same as usual elements :)
Since you're using jQuery anyway, you can use .detach()
var element = $('td:eq(0) span').detach();
$('td:eq(1)').append(element);
Here's a jsfiddle.
Or, as proposed in this answer, you can use a native js solution.