getting html input value inside javascript class - javascript

i am new to javascript and im making a BMI calculator. im making a class in javascript to produce the calculations. currently users could input their height (in feet and inches) and weight. when i run a method within my class. it keeps saying this.feet = null instead of grabbing the value from the input. my javascript code is below. result() is in my html for the submit button.
function calculator(feet,inches,weight) {
this.feet = feet.value;
this.inches = inches.value;
this.weight = weight.value;
this.validateInput = function() {
var errors = [];
if(isNaN(this.feet) || this.feet < 0) {
errors.push("Feet");
}
else {
return this.feet
};
if(isNaN(this.inches) || this.inches < 0 || this.inches > 11) {
errors.push("Inches")
}
else {
return this.inches;
};
if(isNaN(this.weight) || this.weight < 0) {
errors.push("Weight");
}
else {
return this.weight
}
};
this.inchesConverter = function() {
this.feet = parseFloat(feet);
this.inches = parseFloat(inches);
return parseInt(this.feet*12+this.inches);
};
this.bmi = function() {
var height = this.inchesConverter();
var validater = this.validateInput();
for(r = 0; r < errors.length; r++){
if(errors.length > 0) {
return errors[r] + " must be a valid positive number.";
}
else {
parseFloat((validateWeight * 703) / (Math.pow(height, 2))).toFixed(1);
}
}
};
};
var getWeight = document.getElementById('txtWeight');
var getFeet = document.getElementById('txtHeightFeet');
var getInches = document.getElementById('txtHeightInches');
var test = new calculator(getFeet, getInches, getWeight);
function result() {
document.getElementById("lblBMI").innerHTML(test.bmi());
}

Instead of assigning feet.value to this.feet try assigning feet.getAttribute('value')
If you console.log(feet) does it show the proper DOM element?

There is no need to declare the variables with "this."
function calculator(paraFeet,paraInches,paraWeight) {
var feet = paraFeet.value;
var inches = paraInches.value;
var weight = paraWeight.value;
...
you can now remove "this." from every of these variables inside your function

Every browser has JavaScript console on which you can debug your code.
I have some fun to fix it here or there but also you should try it yourself.
Anyway here it is:
function calculator(weight, feet, inches) {
this.weight = weight;
this.feet = feet;
this.inches = inches;
this.validateInput = function() {
var errors = [];
if (!this.validNumber(this.weight, 1000)) {
errors.push("Invalid weight.");
}
if (!this.validNumber(this.feet, 10)) {
errors.push("Invalid hight in feet.");
}
if (!this.validNumber(this.inches, 11)) {
errors.push("Invalid hight in inches.")
}
return errors;
};
this.validNumber = function(num, max) {
if (num.length > 0 && !isNaN(num)) {
var number = parseInt(num);
return number > 0 && number < max + 1;
}
return false;
}
this.displayErrors = function(errors) {
var html = "";
for (error of errors)
html += error + "<br/>";
return html;
};
this.inchesConverter = function() {
var feet = parseInt(this.feet);
var inches = parseInt(this.inches);
return feet * 12 + inches;
};
this.bmi = function() {
var errors = this.validateInput();
if (errors.length > 0) {
return this.displayErrors(errors);
}
var height = this.inchesConverter();
return parseFloat((this.weight * 703) / (Math.pow(height, 2))).toFixed(1);
};
};
function result() {
var getWeight = document.getElementById('txtWeight').value;
var getFeet = document.getElementById('txtHeightFeet').value;
var getInches = document.getElementById('txtHeightInches').value;
var test = new calculator(getWeight, getFeet, getInches);
document.getElementById("lblBMI").innerHTML = test.bmi();
return false;
}
<span>
<label>Weight</label>
<input id="txtWeight">
</span>
<span>
<label>HeightFeet</label>
<input id="txtHeightFeet">
</span>
<span>
<label>HeightInches</label>
<input id="txtHeightInches">
</span>
<button id='run' onClick="return result();">Calculate</button>
<div id="lblBMI"></div>

Figured out what my issue was. The problem arose from my for loop. Working code is posted below!
function calculator(feet,inches,weight) {
this.feet = feet.value;
this.inches = inches.value;
this.weight = weight.value;
this.validateInput = function() {
var errors = [];
if(isNaN(this.feet) || this.feet < 0 || this.feet == "") {
errors.push("feet");
};
if(isNaN(this.inches) || this.inches < 0 || this.inches > 11) {
errors.push("inches")
};
if(isNaN(this.weight) || this.weight < 0 || this.weight == "") {
errors.push("weight");
};
return errors;
console.log(errors);
};
this.inchesConverter = function() {
var parseFeet = parseFloat(this.feet);
var parseInches = parseFloat(this.inches);
return parseInt(parseFeet*12+parseInches);
};
this.bmi = function() {
var height = this.inchesConverter();
var errors = this.validateInput();
if(errors.length > 0) {
for(r = 0; r < errors.length; r++){
return "Please enter a correct number for " + errors[r];
};
}
else {
return parseFloat((this.weight * 703) / (Math.pow(height, 2))).toFixed(1);
};
};
};
function result(){
var getWeight = document.getElementById('txtWeight');
var getFeet = document.getElementById('txtHeightFeet');
var getInches = document.getElementById('txtHeightInches');
var test = new calculator(getFeet, getInches, getWeight);
document.getElementById("lblBMI").innerHTML = test.bmi();
};

Related

Why are my variables being alerted back to me as null?

Why are my variables being alerted back to me as null?
So, I'm trying to pass a string in a variable back to a main page from an external javascript page via alerts.
At first I thought that the javascript wasn't pulling information from the php page properly, then I tried just typing in a variable directly on the javascript page. Both the pulled information and the information that I described on the javascript directly send null.
Now I know for a fact that the varibles name and email are not null, as I literally just defined them.
Here is the code I am having an issue with.
let name = "test";
let email = 11;
let company = document.getElementById($("#Company").value);
let phone = document.getElementById($("#Phone").value);
let city = document.getElementById($("#City").value);
let state = document.getElementById($("#State").value);
let country = document.getElementById($("#Country").value);
alert("Test Alert");
alert(name);
alert(email);
alert(company);
alert(phone);
alert(city);
alert(state);
alert(country);
Here is the full javascript file:
ROICalc3.js
const getErrorMsg2 = lbl =>
`${lbl} must be a valid percent less than or equal to 100.`;
const focusAndSelect = selector => {
const elem = $(selector);
elem.focus();
elem.select();
};
const processEntries = () => {
let ActiveNumberOfMolds = parseFloat($("#activeNumberOfMolds").value);
let PercentOfDownMolds = parseFloat($("#percentOfDownMolds").value);
PercentOfDownMolds = PercentOfDownMolds * .01;
let AverageLaborHours = parseFloat($("#averageLaborHours").value);
let RepairRatePerHour = parseFloat($("#repairRatePerHour").value);
let CostOfCurrentLifter = parseFloat($("#costOfCurrentLifter").value);
let AverageProfitPerPressHour = parseFloat($("#averageProfitPerPressHour").value);
let EstimatedPriceOfAnAcculifter = parseFloat($("#estimatedPriceOfAnAcculifter").value);
let PercentageReductionInLifterFailureUsingAcculignLifters = parseFloat($("#percentageReductionInLifterFailureUsingAcculignLifters").value);
let AverageNumberOfLiftersPerMold = parseFloat($("#averageNumberOfLiftersPerMold").value);
PercentageReductionInLifterFailureUsingAcculignLifters = PercentageReductionInLifterFailureUsingAcculignLifters * .01;
let LifterCostDifference = (EstimatedPriceOfAnAcculifter - CostOfCurrentLifter);
if (isNaN(ActiveNumberOfMolds) || ActiveNumberOfMolds <= 0) {
alert(getErrorMsg("Enter The Active Number Of Molds"));
focusAndSelect("#activeNumberOfMolds");
} else if (isNaN(AverageNumberOfLiftersPerMold) || AverageNumberOfLiftersPerMold <= 0) {
alert(getErrorMsg("Enter the Average Number Of Lifters Per Mold:"));
focusAndSelect("#averageNumberOfLiftersPerMold");
} else if (isNaN(PercentOfDownMolds) || PercentOfDownMolds <= 0) {
alert(getErrorMsg("Enter the Percentage Of Down Molds:"));
focusAndSelect("#percentOfDownMolds");
} else if (isNaN(AverageLaborHours) || AverageLaborHours <= 0) {
alert(getErrorMsg("Enter the Average Labor Hours:"));
focusAndSelect("#averageLaborHours");
} else if (isNaN(RepairRatePerHour) || RepairRatePerHour <= 0) {
alert(getErrorMsg("Enter the repair rate per hour:"));
focusAndSelect("#repairRatePerHour");
} else if (isNaN(AverageProfitPerPressHour) || AverageProfitPerPressHour <= 0) {
alert(getErrorMsg("Enter the average profit per press hour:"));
focusAndSelect("#averageProfitPerPressHour");
} else if (isNaN(CostOfCurrentLifter) || CostOfCurrentLifter <= 0) {
alert(getErrorMsg("Enter the average profit per press hour:"));
focusAndSelect("#costOfCurrentLifter");
} else if (isNaN(EstimatedPriceOfAnAcculifter) || EstimatedPriceOfAnAcculifter <= 0) {
alert(getErrorMsg("Enter the estimated price of an acculifter:"));
focusAndSelect("#estimatedPriceOfAnAcculifter");
} else if (PercentageReductionInLifterFailureUsingAcculignLifters <= 0) {
alert(getErrorMsg("Enter the percentage reduction in lifter failure using accualign lifters:"));
focusAndSelect("#percentageReductionInLifterFailureUsingAcculignLifters");
} else if (PercentOfDownMolds > 1) {
alert(getErrorMsg2("Enter the percentage of down molds:"));
focusAndSelect("#percentOfDownMolds");
} else if (PercentageReductionInLifterFailureUsingAcculignLifters > 1) {
alert(getErrorMsg2("Enter the Percentage Reduction In Lifter Failure Using Accualign Lifters:"));
focusAndSelect("#percentageReductionInLifterFailureUsingAccualignLifters");
} else {
$("#MRRPA").value = (ActiveNumberOfMolds * PercentOfDownMolds);
let mrrpa = parseFloat($("#MRRPA").value);
$("#ANHPL").value = (mrrpa * AverageLaborHours);
let anhpl = parseFloat($("#ANHPL").value);
$("#ALCRFLPM").value = ((anhpl * RepairRatePerHour) + (mrrpa * CostOfCurrentLifter * AverageNumberOfLiftersPerMold));
let alcrflpm = parseFloat($("#ALCRFLPM").value);
$("#PLDDM").value = (AverageProfitPerPressHour * anhpl * .3);
let plddm = parseFloat($("#PLDDM").value);
let eacfl = (plddm + alcrflpm);
$("#EACFL").value = (eacfl);
$("#CDBCLVAL").value = (EstimatedPriceOfAnAcculifter - CostOfCurrentLifter);
let pldtd = (PercentageReductionInLifterFailureUsingAcculignLifters * plddm);
let cdbclval = parseFloat($("#CDBCLVAL").value);
$("#TCDBCLVAL").value = (cdbclval * (ActiveNumberOfMolds * AverageNumberOfLiftersPerMold));
let tcdbclval = parseFloat($("#TCDBCLVAL").value);
let acrnm = ((anhpl * RepairRatePerHour * PercentageReductionInLifterFailureUsingAcculignLifters) + (EstimatedPriceOfAnAcculifter * AverageNumberOfLiftersPerMold * ActiveNumberOfMolds * PercentOfDownMolds * PercentageReductionInLifterFailureUsingAcculignLifters));
let cdnlptrc = (tcdbclval + acrnm + pldtd);
let rlfcical = (eacfl - cdnlptrc);
$("#RLFCICAL").value = rlfcical;
$("#EMUUPI").value = ((tcdbclval / rlfcical) * 12).toFixed(2);;
let emuupi = parseFloat($("#EMUUPI").value);
console.log("EACFL: " + eacfl);
console.log("cdnlptrc: " + cdnlptrc);
document.getElementById("MRRPA").innerHTML = mrrpa + " Molds";
document.getElementById("ANHPL").innerHTML = anhpl + " Hours";
document.getElementById("ALCRFLPM").innerHTML = "$" + alcrflpm;
document.getElementById("PLDDM").innerHTML = "$" + plddm;
document.getElementById("CDBCLVAL").innerHTML = "$" + cdbclval;
document.getElementById("TCDBCLVAL").innerHTML = "$" + tcdbclval;
document.getElementById("RLFCICAL").innerHTML = "$" + rlfcical;
document.getElementById("EACFL").innerHTML = "$" + eacfl;
document.getElementById("EMUUPI").innerHTML = emuupi + " Months";
document.getElementById("ACRNM").innerHTML = "$" + acrnm;
document.getElementById("PLDTD").innerHTML = "$" + pldtd;
document.getElementById("CDNLPTRC").innerHTML = "$" + cdnlptrc;
if (rlfcical > 0) {
document.getElementById("RLFCICAL").style.color = "green";
} else {
document.getElementById("RLFCICAL").style.color = "red";
}
if (eacfl > 0) {
document.getElementById("EACFL").style.color = "red";
} else {
document.getElementById("EACFL").style.color = "green";
}
if (alcrflpm > 0) {
document.getElementById("ALCRFLPM").style.color = "red";
} else {
document.getElementById("ALCRFLPM").style.color = "green";
}
if (plddm > 0) {
document.getElementById("PLDDM").style.color = "red";
} else {
document.getElementById("PLDDM").style.color = "green";
}
if (tcdbclval > 0) {
document.getElementById("TCDBCLVAL").style.color = "red";
} else {
document.getElementById("TCDBCLVAL").style.color = "green";
}
if (cdbclval) {
document.getElementById("CDBCLVAL").style.color = "red";
} else {
document.getElementById("CDBCLVAL").style.color = "green";
}
if (emuupi > 0) {
document.getElementById("EMUUPI").style.color = "green";
} else {
document.getElementById("EMUUPI").style.color = "red";
}
if (anhpl > 0) {
document.getElementById("ANHPL").style.color = "red";
} else {
document.getElementById("ANHPL").style.color = "green";
}
if (mrrpa > 0) {
document.getElementById("MRRPA").style.color = "red";
} else {
document.getElementById("MRRPA").style.color = "green";
}
if (acrnm > 0) {
document.getElementById("ACRNM").style.color = "red";
} else {
document.getElementById("ACRNM").style.color = "green";
}
if (pldtd > 0) {
document.getElementById("PLDTD").style.color = "red";
} else {
document.getElementById("PLDTD").style.color = "green";
}
if (cdnlptrc > 0) {
document.getElementById("CDNLPTRC").style.color = "red";
} else {
document.getElementById("CDNLPTRC").style.color = "green";
}
let name = "test";
let email = 11;
let company = document.getElementById($("#Company").value);
let phone = document.getElementById($("#Phone").value);
let city = document.getElementById($("#City").value);
let state = document.getElementById($("#State").value);
let country = document.getElementById($("#Country").value);
alert("Test Alert");
alert(name);
alert(email);
alert(company);
alert(phone);
alert(city);
alert(state);
alert(country);
let result = document.querySelector('.result');
// Creating a XHR object
let xhr = new XMLHttpRequest();
let url = "https://staging-dmecompany.kinsta.cloud/Submissions/submitjson.php";
// open a connection
xhr.open("POST", url, true);
// Set the request header i.e. which type of content you are sending
xhr.setRequestHeader("Content-Type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
document.getElementById("result").innerHTML = this.responseText;
}
};
// Converting JSON data to string
var data = JSON.stringify({
"Name": name,
"Email": email,
"Company": company,
"Phone": phone,
"City": city,
"State": state,
"Country": country,
"ActiveNumberOfMolds": ActiveNumberOfMolds,
"PercentOfDownMolds": PercentOfDownMolds,
"Average Labor Hours": AverageLaborHours,
"RepairRatePerHour": RepairRatePerHour,
"AverageProfitPerPressHour": AverageProfitPerPressHour,
"AverageNumberOfLiftersPerMold": AverageNumberOfLiftersPerMold,
"rlfcical": rlfcical,
"LifterCostDifference": LifterCostDifference,
"anhpl": anhpl,
"alcrflpm": alcrflpm,
"plddm": plddm,
"cdbclval": cdbclval,
"pldtd": pldtd,
"cdbclval": cdbclval,
"emuupi": emuupi,
"mrrpa": mrrpa,
"acrnm": acrnm,
"pldtd": pldtd,
"cdnlptrc": cdnlptrc
});
// Sending data with the request
xhr.send(data);
}
};
document.addEventListener("DOMContentLoaded", () => {
$("#calculate").addEventListener("click", processEntries);
$("#activeNumberOfMolds").focus();
});
Can you tell me why these variables are getting alerted back to me as null?
Edit: #1:
I tried swapping the code to this:
let name = "test";
let email = 11;
let company = document.getElementById("Company").value;
let phone = document.getElementById("Phone").value;
let city = document.getElementById("City").value;
let state = document.getElementById("State").value;
let country = document.getElementById("Country").value;
alert("Test Alert");
alert(name);
alert(email);
alert(company);
alert(phone);
alert(city);
alert(state);
alert(country);
The first alert had, "test"
The second alert had, "11"
All of the rest of the alerts were, "Undefined".
The alerts seem to be feeding back data now if the variables are described in the javascript code itself. I don't seem to be able to pull them from my php file.
.value should not be in the argument to document.getElementById(), it should be used on the result of this.
And you shouldn't call $() or use the # prefix in the argument to getElementById(), the argument should just be the ID by itself.
let company = document.getElementById($("#Company").value);
should be
let company = document.getElementById("Company").value;
Or if $() is an abbreviation for document.querySelector(), you can write
let company = $("#Company").value;
If it's jQuery, then the correct syntax is
let company = $("#Company").val();

No results display when running JavaScript

I am stumped. I am not receiving any errors or undefined errors when running this code just a blank return and then a new command line. I've run it about 100 times in the command prompt and still nothing. I figured after 100 times it should display the "Congratulations message". Can anyone take a look and see what I am missing? Thank you in advance.
//Player Class
function Player(name, weapons) {
this.playerName = name;
this.playerHealth = 10;
this.playerStrength = 2;
this.playerWeapons = weapons;
}
Player.prototype.applyDamage = function(damage) {
this.playerHealth = this.playerHealth - damage;
console.log(this.playerName + " " + "has sustained " + " " + this.playerHealth + " " + "amount of damage.");
}
Player.prototype.isAlive = function() {
if(this.playerHealth > 0)
return true;
else
return false;
}
Player.prototype.attacksWith = function() {
var random = Math.floor(Math.random() * 8);
return (this.weapon[random]);
}
//Minion Class
function Minion(minion, health, strength) {
this.minionName = 'Minion';
this.minionHealth = 5;
this.minionStrength = 2;
}
Minion.prototype.applyDamage = function(damage) {
this.minionHealth = this.minionHealth - damage;
console.log(this.minionName + " " + "has sustained " + " " + this.minionHealth + " " + "amount of damage.");
}
Minion.prototype.isAlive = function() {
if(this.minionHealth > 0)
return true;
else
return false;
}
Minion.prototype.attack = function(playerName) {
playerName.applyDamage(this.minionHealth);
}
//Weapons Class
function Weapons(weapon) {
this.weaponName = weapon;
this.weapondamage = Math.floor(Math.random() * 5) + 1;
}
var weaponsCache = [];
for (var i = 0; i < 8; i++) {
var axe = new Weapons("skullCracker");
var hxfx = new Weapons("Hexaflexagon");
var blade = new Weapons("Balmung");
var mario = new Weapons("cappy");
var fire = new Weapons("Fire Breath");
var staff = new Weapons("Magic Staff");
var hrp = new Weapons("Harpe");
var CobaltWep = new Weapons("Cobalt Rifle");
var w = new Weapons([i]);
weaponsCache[i] = w;
}
var player = [];
var i = 0;
while (i < 8) {
var m = new Player();
player[i] = m;
i++;
}
//Game Class
function Game(players, minions) {
this.players = [];
this.minions = [];
}
function attack(player, minion) {
while (playerName.isAlive() && minionName.isAlive()) {
actualDamage = player.strength * this.damage();
minion.applyDamage(actualDamage);
if (minion.isAlive())
minion.attack(player);
else
break;
}
}
function createMinions() {
var i = 0;
while (i > 20) {
var m = new Minion();
minion[i] = m;
i++;
}
}
function createPlayers() {
var player = []; {
var ph = new Player("Prophetic Hamster", weaponsCache);
var mm = new Player("Mighty Mathematician", weaponsCache);
var sieg = new Player ("Siegfried", weaponsCache);
var bd = new Player ("Blue Dragon", weaponsCache);
var ip = new Player("Iron Professor", weaponsCache)
}
Game.prototype.play = function() {
console.log("Simulating Battle...");
createMinion();
createPlayer();
var i = 0,
count = 0;
while (i < 20) {
if (minions[i].isAlive())
count++;
}
if (count == 20) {
i = 0;
var flag = 0;
while (i < 8) {
if (players[i].isAlive())
flag++;
}
while (count == 20 && flag > 0) {
var randomPlayer, randomMinion;
randomPlayer = Math.floor(Math.random() * 8);
randomMinion = math.floor(Math.random() * 20);
weapon = player.attackWith();
attack(minions);
attack(players);
}
count = 0;
i = 0;
while (i > 20) {
if (minions[i].isAlive())
count++;
}
flag = 0;
i = 0;
while (i < 8) {
if (players[i].isAlive())
flag++;
}
if (flag > count)
console.log("Congratulations!! You have defeated Scarlet Byte");
}
}
}

Javascript network with labels and weighted edges

I have been searching for quite a while now and I'm not able to find a simple JS library to make a network in which:
The nodes have labels
The edge thickness is proportional to the weight
Able to spread the nodes so that it doesn't get messy.
I found a script on bl.ocks.org which fits my needs, but when I use a lot of nodes it's getting quite messy:
I use this as input:
target,source,weight
woooooow,notgood,70.0
woooooow,gainzz,32.004950495049506
woooooow,test,33.86138613861386
woooooow,peanutss,20.866336633663366
nicecode,woooooow,22.103960396039604
woooooow,oreo,20.742574257425744
bread,woooooow,37.945544554455445
jam,nutella,20.123762376237625
bread,nutsarelol,20.866336633663366
etc
Question
Any ideas which code/library I can use to create a graph like the graph above but with more spreading of the nodes?
JS code
/*
Author: Corneliu S. (github.com/upphiminn)
This is a javascript implementation of the Louvain
community detection algorithm (http://arxiv.org/abs/0803.0476)
Based on https://bitbucket.org/taynaud/python-louvain/overview
*/
(function(){
jLouvain = function(){
//Constants
var __PASS_MAX = -1
var __MIN = 0.0000001
//Local vars
var original_graph_nodes;
var original_graph_edges;
var original_graph = {};
var partition_init;
//Helpers
function make_set(array){
var set = {};
array.forEach(function(d,i){
set[d] = true;
});
return Object.keys(set);
};
function obj_values(obj){
var vals = [];
for( var key in obj ) {
if ( obj.hasOwnProperty(key) ) {
vals.push(obj[key]);
}
}
return vals;
};
function get_degree_for_node(graph, node){
var neighbours = graph._assoc_mat[node] ? Object.keys(graph._assoc_mat[node]) : [];
var weight = 0;
neighbours.forEach(function(neighbour,i){
var value = graph._assoc_mat[node][neighbour] || 1;
if(node == neighbour)
value *= 2;
weight += value;
});
return weight;
};
function get_neighbours_of_node(graph, node){
if(typeof graph._assoc_mat[node] == 'undefined')
return [];
var neighbours = Object.keys(graph._assoc_mat[node]);
return neighbours;
}
function get_edge_weight(graph, node1, node2){
return graph._assoc_mat[node1] ? graph._assoc_mat[node1][node2] : undefined;
}
function get_graph_size(graph){
var size = 0;
graph.edges.forEach(function(edge){
size += edge.weight;
});
return size;
}
function add_edge_to_graph(graph, edge){
update_assoc_mat(graph, edge);
var edge_index = graph.edges.map(function(d){
return d.source+'_'+d.target;
}).indexOf(edge.source+'_'+edge.target);
if(edge_index != -1)
graph.edges[edge_index].weight = edge.weight;
else
graph.edges.push(edge);
}
function make_assoc_mat(edge_list){
var mat = {};
edge_list.forEach(function(edge, i){
mat[edge.source] = mat[edge.source] || {};
mat[edge.source][edge.target] = edge.weight;
mat[edge.target] = mat[edge.target] || {};
mat[edge.target][edge.source] = edge.weight;
});
return mat;
}
function update_assoc_mat(graph, edge){
graph._assoc_mat[edge.source] = graph._assoc_mat[edge.source] || {};
graph._assoc_mat[edge.source][edge.target] = edge.weight;
graph._assoc_mat[edge.target] = graph._assoc_mat[edge.target] || {};
graph._assoc_mat[edge.target][edge.source] = edge.weight;
}
function clone(obj){
if(obj == null || typeof(obj) != 'object')
return obj;
var temp = obj.constructor();
for(var key in obj)
temp[key] = clone(obj[key]);
return temp;
}
//Core-Algorithm Related
function init_status(graph, status, part){
status['nodes_to_com'] = {};
status['total_weight'] = 0;
status['internals'] = {};
status['degrees'] = {};
status['gdegrees'] = {};
status['loops'] = {};
status['total_weight'] = get_graph_size(graph);
if(typeof part == 'undefined'){
graph.nodes.forEach(function(node,i){
status.nodes_to_com[node] = i;
var deg = get_degree_for_node(graph, node);
if (deg < 0)
throw 'Bad graph type, use positive weights!';
status.degrees[i] = deg;
status.gdegrees[node] = deg;
status.loops[node] = get_edge_weight(graph, node, node) || 0;
status.internals[i] = status.loops[node];
});
}else{
graph.nodes.forEach(function(node,i){
var com = part[node];
status.nodes_to_com[node] = com;
var deg = get_degree_for_node(graph, node);
status.degrees[com] = (status.degrees[com] || 0) + deg;
status.gdegrees[node] = deg;
var inc = 0.0;
var neighbours = get_neighbours_of_node(graph, node);
neighbours.forEach(function(neighbour, i){
var weight = graph._assoc_mat[node][neighbour];
if (weight <= 0){
throw "Bad graph type, use positive weights";
}
if(part[neighbour] == com){
if (neighbour == node){
inc += weight;
}else{
inc += weight/2.0;
}
}
});
status.internals[com] = (status.internals[com] || 0) + inc;
});
}
}
function __modularity(status){
var links = status.total_weight;
var result = 0.0;
var communities = make_set(obj_values(status.nodes_to_com));
communities.forEach(function(com,i){
var in_degree = status.internals[com] || 0 ;
var degree = status.degrees[com] || 0 ;
if(links > 0){
result = result + in_degree / links - Math.pow((degree / (2.0*links)), 2);
}
});
return result;
}
function __neighcom(node, graph, status){
// compute the communities in the neighb. of the node, with the graph given by
// node_to_com
var weights = {};
var neighboorhood = get_neighbours_of_node(graph, node);//make iterable;
neighboorhood.forEach(function(neighbour, i){
if(neighbour != node){
var weight = graph._assoc_mat[node][neighbour] || 1;
var neighbourcom = status.nodes_to_com[neighbour];
weights[neighbourcom] = (weights[neighbourcom] || 0) + weight;
}
});
return weights;
}
function __insert(node, com, weight, status){
//insert node into com and modify status
status.nodes_to_com[node] = +com;
status.degrees[com] = (status.degrees[com] || 0) + (status.gdegrees[node]||0);
status.internals[com] = (status.internals[com] || 0) + weight + (status.loops[node]||0);
}
function __remove(node, com, weight, status){
//remove node from com and modify status
status.degrees[com] = ((status.degrees[com] || 0) - (status.gdegrees[node] || 0));
status.internals[com] = ((status.internals[com] || 0) - weight -(status.loops[node] ||0));
status.nodes_to_com[node] = -1;
}
function __renumber(dict){
var count = 0;
var ret = clone(dict); //deep copy :)
var new_values = {};
var dict_keys = Object.keys(dict);
dict_keys.forEach(function(key){
var value = dict[key];
var new_value = typeof new_values[value] =='undefined' ? -1 : new_values[value];
if(new_value == -1){
new_values[value] = count;
new_value = count;
count = count + 1;
}
ret[key] = new_value;
});
return ret;
}
function __one_level(graph, status){
//Compute one level of the Communities Dendogram.
var modif = true,
nb_pass_done = 0,
cur_mod = __modularity(status),
new_mod = cur_mod;
while (modif && nb_pass_done != __PASS_MAX){
cur_mod = new_mod;
modif = false;
nb_pass_done += 1
graph.nodes.forEach(function(node,i){
var com_node = status.nodes_to_com[node];
var degc_totw = (status.gdegrees[node] || 0) / (status.total_weight * 2.0);
var neigh_communities = __neighcom(node, graph, status);
__remove(node, com_node, (neigh_communities[com_node] || 0.0), status);
var best_com = com_node;
var best_increase = 0;
var neigh_communities_entries = Object.keys(neigh_communities);//make iterable;
neigh_communities_entries.forEach(function(com,i){
var incr = neigh_communities[com] - (status.degrees[com] || 0.0) * degc_totw;
if (incr > best_increase){
best_increase = incr;
best_com = com;
}
});
__insert(node, best_com, neigh_communities[best_com] || 0, status);
if(best_com != com_node)
modif = true;
});
new_mod = __modularity(status);
if(new_mod - cur_mod < __MIN)
break;
}
}
function induced_graph(partition, graph){
var ret = {nodes:[], edges:[], _assoc_mat: {}};
var w_prec, weight;
//add nodes from partition values
var partition_values = obj_values(partition);
ret.nodes = ret.nodes.concat(make_set(partition_values)); //make set
graph.edges.forEach(function(edge,i){
weight = edge.weight || 1;
var com1 = partition[edge.source];
var com2 = partition[edge.target];
w_prec = (get_edge_weight(ret, com1, com2) || 0);
var new_weight = (w_prec + weight);
add_edge_to_graph(ret, {'source': com1, 'target': com2, 'weight': new_weight});
});
return ret;
}
function partition_at_level(dendogram, level){
var partition = clone(dendogram[0]);
for(var i = 1; i < level + 1; i++ )
Object.keys(partition).forEach(function(key,j){
var node = key;
var com = partition[key];
partition[node] = dendogram[i][com];
});
return partition;
}
function generate_dendogram(graph, part_init){
if(graph.edges.length == 0){
var part = {};
graph.nodes.forEach(function(node,i){
part[node] = node;
});
return part;
}
var status = {};
init_status(original_graph, status, part_init);
var mod = __modularity(status);
var status_list = [];
__one_level(original_graph, status);
var new_mod = __modularity(status);
var partition = __renumber(status.nodes_to_com);
status_list.push(partition);
mod = new_mod;
var current_graph = induced_graph(partition, original_graph);
init_status(current_graph, status);
while (true){
__one_level(current_graph, status);
new_mod = __modularity(status);
if(new_mod - mod < __MIN)
break;
partition = __renumber(status.nodes_to_com);
status_list.push(partition);
mod = new_mod;
current_graph = induced_graph(partition, current_graph);
init_status(current_graph, status);
}
return status_list;
}
var core = function(){
var status = {};
var dendogram = generate_dendogram(original_graph, partition_init);
return partition_at_level(dendogram, dendogram.length - 1);
};
core.nodes = function(nds){
if(arguments.length > 0){
original_graph_nodes = nds;
}
return core;
};
core.edges = function(edgs){
if(typeof original_graph_nodes == 'undefined')
throw 'Please provide the graph nodes first!';
if(arguments.length > 0){
original_graph_edges = edgs;
var assoc_mat = make_assoc_mat(edgs);
original_graph = { 'nodes': original_graph_nodes,
'edges': original_graph_edges,
'_assoc_mat': assoc_mat };
}
return core;
};
core.partition_init = function(prttn){
if(arguments.length > 0){
partition_init = prttn;
}
return core;
};
return core;
}
})();

how to I get rid of undefined(s) and the other problems in my code?

I've tried this a thousand different ways in a thousand different times and my JS code won't come out the way I want it. When I run it in the Mozilla scratchpad, I get "userHand is undefined" and the second printHand shows as undefined, too. Could someone show me where are the errors in my blackjack game?
function Card (s, n) {
var suit = s;
var number = n;
this.getNumber = function () {
return number;
};
this.getSuit = function () {
return suit;
};
this.getValue = function () {
if (number > 10) {
return 10;
} else if (number === 1) {
return 11;
} else {
return number;
}
};
}
var cardNames = {1:"Ace", 2:"2", 3:"3", 4:"4", 5:"5", 6:"6", 7:"7", 8:"8", 9:"9", 10:"10", 11:"Joker", 12:"Queen", 13:"King"};
var suitNames = {1:"Clubs", 2:"Diamonds", 3:"Hearts", 4:"Spades"};
var deal = function () {
var s = Math.floor(Math.random() * 4 + 1);
var n = Math.floor(Math.random() * 13 + 1);
return new Card(s, n);
};
function Hand(){
var cards = [];
cards.push(deal());
cards.push(deal());
this.getHand = function () {
return cards;
};
this.score = function () {
var score;
for (i = 0; i < cards.length; i++) {
score = score + cards[i].getValue();
}
for (i = 0; i < cards.length; i++) {
if (score > 21 && cards[i].getValue() === 11) {
score = score - 10;
}
} return score;
};
this.printHand = function () {
for (i = 0; i < cards.length; i++) {
var hand;
if (i === 0) {
hand = cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
} else {
hand = hand + " and a " + cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
}
} alert(hand);
};
this.hitMe = function () {
cards.push(deal());
};
}
var playAsDealer = function () {
var playDealer = new Hand();
while (playDealer.score() < 17) {
playDealer.hitMe();
}
this.printHand = function () {
return playDealer.printHand();
};
this.score = function () {
return playDealer.score();
};
};
var playAsUser = function () {
var playUser = new Hand();
this.printHand = function () {
return playUser.printHand();
};
this.score = function () {
return playUser.score();
};
var decision = confirm("Your hand is " + playUser.printHand() + ". Click OK to hit or Cancel to stand");
for (i = 0; decision !== false; i++) {
playUser.hitMe();
decision = confirm("Your hand is " + playUser.printHand() + ". Click OK to hit or Cancel to stand");
}
};
var declareWinner = function (userHand, dealerHand) {
if ((userHand.score < dealerHand.score) || userHand.score > 21) {
return "You lose.";
} else if (userHand.score > dealerHand.score) {
return "You win.";
} else {
return "You tied.";
}
};
var playGame = function () {
var user = playAsUser();
var dealer = playAsDealer();
declareWinner(user, dealer);
console.log("User got " + user.printHand());
console.log("Dealer got " + dealer.printHand());
};
playGame();
You aren't returning nothing on printHand()
I just added the return statement and worked. See this fiddle
this.printHand = function () {
for (i = 0; i < cards.length; i++) {
var hand;
if (i === 0) {
hand = cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
} else {
hand = hand + " and a " + cardNames[cards[i].getNumber()] + " of " + suitNames[cards[i].getSuit()];
}
}
//alert(hand); //remove this alert
return hand; // <----- solution
};

modifying webkitdragdrop.js use classes instead of ID

I've found a script that seems perfect for my needs, but it uses IDs, rather than classes to create ipad-friendly drag & drop elements.
I really need it to use classes, as the draggable elements could potentially be in the thousands.
[edit] I'm not that great at javascript and am having difficulties in understanding how I could alter the script to use classes instead of IDs.
I have also contacted the script author, but have had no reply from him.
I'm offering this bounty as I've not had any response to my original query.
Please could someone change the script below so that it uses classes? [/edit]
Below is the script in its entirety, and here is the script page (API was not helpful to me in being able to use classes vs id).
// webkitdragdrop.js v1.0, Mon May 15 2010
//
// Copyright (c) 2010 Tommaso Buvoli (http://www.tommasobuvoli.com)
// No Extra Libraries are required, simply download this file, add it to your pages!
//
// To See this library in action, grab an ipad and head over to http://www.gotproject.com
// webkitdragdrop is freely distributable under the terms of an MIT-style license.
//Description
// Because this library was designed to run without requiring any other libraries, several basic helper functions were implemented
// 6 helper functons in this webkit_tools class have been taked directly from Prototype 1.6.1 (http://prototypejs.org/) (c) 2005-2009 Sam Stephenson
var webkit_tools =
{
//$ function - simply a more robust getElementById
$:function(e)
{
if(typeof(e) == 'string')
{
return document.getElementById(e);
}
return e;
},
//extend function - copies the values of b into a (Shallow copy)
extend:function(a,b)
{
for (var key in b)
{
a[key] = b[key];
}
return a;
},
//empty function - used as defaut for events
empty:function()
{
},
//remove null values from an array
compact:function(a)
{
var b = []
var l = a.length;
for(var i = 0; i < l; i ++)
{
if(a[i] !== null)
{
b.push(a[i]);
}
}
return b;
},
//DESCRIPTION
// This function was taken from the internet (http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/) and returns
// the computed style of an element independantly from the browser
//INPUT
// oELM (DOM ELEMENT) element whose style should be extracted
// strCssRule element
getCalculatedStyle:function(oElm, strCssRule)
{
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle){
strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
}
else if(oElm.currentStyle){
strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
return p1.toUpperCase();
});
strValue = oElm.currentStyle[strCssRule];
}
return strValue;
},
//bindAsEventListener function - used to bind events
bindAsEventListener:function(f,object)
{
var __method = f;
return function(event) {
__method.call(object, event || window.event);
};
},
//cumulative offset - courtesy of Prototype (http://www.prototypejs.org)
cumulativeOffset:function(element)
{
var valueT = 0, valueL = 0;
do {
valueT += element.offsetTop || 0;
valueL += element.offsetLeft || 0;
if (element.offsetParent == document.body)
if (element.style.position == 'absolute') break;
element = element.offsetParent;
} while (element);
return {left : valueL, top : valueT};
},
//getDimensions - courtesy of Prototype (http://www.prototypejs.org)
getDimensions: function(element)
{
var display = element.style.display;
if (display != 'none' && display != null) // Safari bug
return {width: element.offsetWidth, height: element.offsetHeight};
var els = element.style;
var originalVisibility = els.visibility;
var originalPosition = els.position;
var originalDisplay = els.display;
els.visibility = 'hidden';
if (originalPosition != 'fixed') // Switching fixed to absolute causes issues in Safari
els.position = 'absolute';
els.display = 'block';
var originalWidth = element.clientWidth;
var originalHeight = element.clientHeight;
els.display = originalDisplay;
els.position = originalPosition;
els.visibility = originalVisibility;
return {width: originalWidth, height: originalHeight};
},
//hasClassName - courtesy of Prototype (http://www.prototypejs.org)
hasClassName: function(element, className)
{
var elementClassName = element.className;
return (elementClassName.length > 0 && (elementClassName == className ||
new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
},
//addClassName - courtesy of Prototype (http://www.prototypejs.org)
addClassName: function(element, className)
{
if (!this.hasClassName(element, className))
element.className += (element.className ? ' ' : '') + className;
return element;
},
//removeClassName - courtesy of Prototype (http://www.prototypejs.org)
removeClassName: function(element, className)
{
element.className = this.strip(element.className.replace(new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' '));
return element;
},
//strip - courtesy of Prototype (http://www.prototypejs.org)
strip:function(s)
{
return s.replace(/^\s+/, '').replace(/\s+$/, '');
}
}
//Description
// Droppable fire events when a draggable is dropped on them
var webkit_droppables = function()
{
this.initialize = function()
{
this.droppables = [];
this.droppableRegions = [];
}
this.add = function(root, instance_props)
{
root = webkit_tools.$(root);
var default_props = {accept : [], hoverClass : null, onDrop : webkit_tools.empty, onOver : webkit_tools.empty, onOut : webkit_tools.empty};
default_props = webkit_tools.extend(default_props, instance_props || {});
this.droppables.push({r : root, p : default_props});
}
this.remove = function(root)
{
root = webkit_tools.$(root);
var d = this.droppables;
var i = d.length;
while(i--)
{
if(d[i].r == root)
{
d[i] = null;
this.droppables = webkit_tools.compact(d);
return true;
}
}
return false;
}
//calculate position and size of all droppables
this.prepare = function()
{
var d = this.droppables;
var i = d.length;
var dR = [];
var r = null;
while(i--)
{
r = d[i].r;
if(r.style.display != 'none')
{
dR.push({i : i, size : webkit_tools.getDimensions(r), offset : webkit_tools.cumulativeOffset(r)})
}
}
this.droppableRegions = dR;
}
this.finalize = function(x,y,r,e)
{
var indices = this.isOver(x,y);
var index = this.maxZIndex(indices);
var over = this.process(index,r);
if(over)
{
this.drop(index, r,e);
}
this.process(-1,r);
return over;
}
this.check = function(x,y,r)
{
var indices = this.isOver(x,y);
var index = this.maxZIndex(indices);
return this.process(index,r);
}
this.isOver = function(x, y)
{
var dR = this.droppableRegions;
var i = dR.length;
var active = [];
var r = 0;
var maxX = 0;
var minX = 0;
var maxY = 0;
var minY = 0;
while(i--)
{
r = dR[i];
minY = r.offset.top;
maxY = minY + r.size.height;
if((y > minY) && (y < maxY))
{
minX = r.offset.left;
maxX = minX + r.size.width;
if((x > minX) && (x < maxX))
{
active.push(r.i);
}
}
}
return active;
}
this.maxZIndex = function(indices)
{
var d = this.droppables;
var l = indices.length;
var index = -1;
var maxZ = -100000000;
var curZ = 0;
while(l--)
{
curZ = parseInt(d[indices[l]].r.style.zIndex || 0);
if(curZ > maxZ)
{
maxZ = curZ;
index = indices[l];
}
}
return index;
}
this.process = function(index, draggableRoot)
{
//only perform update if a change has occured
if(this.lastIndex != index)
{
//remove previous
if(this.lastIndex != null)
{
var d = this.droppables[this.lastIndex]
var p = d.p;
var r = d.r;
if(p.hoverClass)
{
webkit_tools.removeClassName(r,p.hoverClass);
}
p.onOut();
this.lastIndex = null;
this.lastOutput = false;
}
//add new
if(index != -1)
{
var d = this.droppables[index]
var p = d.p;
var r = d.r;
if(this.hasClassNames(draggableRoot, p.accept))
{
if(p.hoverClass)
{
webkit_tools.addClassName(r,p.hoverClass);
}
p.onOver();
this.lastIndex = index;
this.lastOutput = true;
}
}
}
return this.lastOutput;
}
this.drop = function(index, r, e)
{
if(index != -1)
{
this.droppables[index].p.onDrop(r,e);
}
}
this.hasClassNames = function(r, names)
{
var l = names.length;
if(l == 0){return true}
while(l--)
{
if(webkit_tools.hasClassName(r,names[l]))
{
return true;
}
}
return false;
}
this.initialize();
}
webkit_drop = new webkit_droppables();
//Description
//webkit draggable - allows users to drag elements with their hands
var webkit_draggable = function(r, ip)
{
this.initialize = function(root, instance_props)
{
this.root = webkit_tools.$(root);
var default_props = {scroll : false, revert : false, handle : this.root, zIndex : 1000, onStart : webkit_tools.empty, onEnd : webkit_tools.empty};
this.p = webkit_tools.extend(default_props, instance_props || {});
default_props.handle = webkit_tools.$(default_props.handle);
this.prepare();
this.bindEvents();
}
this.prepare = function()
{
var rs = this.root.style;
//set position
if(webkit_tools.getCalculatedStyle(this.root,'position') != 'absolute')
{
rs.position = 'relative';
}
//set top, right, bottom, left
rs.top = rs.top || '0px';
rs.left = rs.left || '0px';
rs.right = "";
rs.bottom = "";
//set zindex;
rs.zIndex = rs.zIndex || '0';
}
this.bindEvents = function()
{
var handle = this.p.handle;
this.ts = webkit_tools.bindAsEventListener(this.touchStart, this);
this.tm = webkit_tools.bindAsEventListener(this.touchMove, this);
this.te = webkit_tools.bindAsEventListener(this.touchEnd, this);
handle.addEventListener("touchstart", this.ts, false);
handle.addEventListener("touchmove", this.tm, false);
handle.addEventListener("touchend", this.te, false);
}
this.destroy = function()
{
var handle = this.p.handle;
handle.removeEventListener("touchstart", this.ts);
handle.removeEventListener("touchmove", this.tm);
handle.removeEventListener("touchend", this.te);
}
this.set = function(key, value)
{
this.p[key] = value;
}
this.touchStart = function(event)
{
//prepare needed variables
var p = this.p;
var r = this.root;
var rs = r.style;
var t = event.targetTouches[0];
//get position of touch
touchX = t.pageX;
touchY = t.pageY;
//set base values for position of root
rs.top = this.root.style.top || '0px';
rs.left = this.root.style.left || '0px';
rs.bottom = null;
rs.right = null;
var rootP = webkit_tools.cumulativeOffset(r);
var cp = this.getPosition();
//save event properties
p.rx = cp.x;
p.ry = cp.y;
p.tx = touchX;
p.ty = touchY;
p.z = parseInt(this.root.style.zIndex);
//boost zIndex
rs.zIndex = p.zIndex;
webkit_drop.prepare();
p.onStart();
}
this.touchMove = function(event)
{
event.preventDefault();
event.stopPropagation();
//prepare needed variables
var p = this.p;
var r = this.root;
var rs = r.style;
var t = event.targetTouches[0];
if(t == null){return}
var curX = t.pageX;
var curY = t.pageY;
var delX = curX - p.tx;
var delY = curY - p.ty;
rs.left = p.rx + delX + 'px';
rs.top = p.ry + delY + 'px';
//scroll window
if(p.scroll)
{
s = this.getScroll(curX, curY);
if((s[0] != 0) || (s[1] != 0))
{
window.scrollTo(window.scrollX + s[0], window.scrollY + s[1]);
}
}
//check droppables
webkit_drop.check(curX, curY, r);
//save position for touchEnd
this.lastCurX = curX;
this.lastCurY = curY;
}
this.touchEnd = function(event)
{
var r = this.root;
var p = this.p;
var dropped = webkit_drop.finalize(this.lastCurX, this.lastCurY, r, event);
if(((p.revert) && (!dropped)) || (p.revert === 'always'))
{
//revert root
var rs = r.style;
rs.top = (p.ry + 'px');
rs.left = (p.rx + 'px');
}
r.style.zIndex = this.p.z;
this.p.onEnd();
}
this.getPosition = function()
{
var rs = this.root.style;
return {x : parseInt(rs.left || 0), y : parseInt(rs.top || 0)}
}
this.getScroll = function(pX, pY)
{
//read window variables
var sX = window.scrollX;
var sY = window.scrollY;
var wX = window.innerWidth;
var wY = window.innerHeight;
//set contants
var scroll_amount = 10; //how many pixels to scroll
var scroll_sensitivity = 100; //how many pixels from border to start scrolling from.
var delX = 0;
var delY = 0;
//process vertical y scroll
if(pY - sY < scroll_sensitivity)
{
delY = -scroll_amount;
}
else
if((sY + wY) - pY < scroll_sensitivity)
{
delY = scroll_amount;
}
//process horizontal x scroll
if(pX - sX < scroll_sensitivity)
{
delX = -scroll_amount;
}
else
if((sX + wX) - pX < scroll_sensitivity)
{
delX = scroll_amount;
}
return [delX, delY]
}
//contructor
this.initialize(r, ip);
}
//Description
//webkit_click class. manages click events for draggables
var webkit_click = function(r, ip)
{
this.initialize = function(root, instance_props)
{
var default_props = {onClick : webkit_tools.empty};
this.root = webkit_tools.$(root);
this.p = webkit_tools.extend(default_props, instance_props || {});
this.bindEvents();
}
this.bindEvents = function()
{
var root = this.root;
//bind events to local scope
this.ts = webkit_tools.bindAsEventListener(this.touchStart,this);
this.tm = webkit_tools.bindAsEventListener(this.touchMove,this);
this.te = webkit_tools.bindAsEventListener(this.touchEnd,this);
//add Listeners
root.addEventListener("touchstart", this.ts, false);
root.addEventListener("touchmove", this.tm, false);
root.addEventListener("touchend", this.te, false);
this.bound = true;
}
this.touchStart = function()
{
this.moved = false;
if(this.bound == false)
{
this.root.addEventListener("touchmove", this.tm, false);
this.bound = true;
}
}
this.touchMove = function()
{
this.moved = true;
this.root.removeEventListener("touchmove", this.tm);
this.bound = false;
}
this.touchEnd = function()
{
if(this.moved == false)
{
this.p.onClick();
}
}
this.setEvent = function(f)
{
if(typeof(f) == 'function')
{
this.p.onClick = f;
}
}
this.unbind = function()
{
var root = this.root;
root.removeEventListener("touchstart", this.ts);
root.removeEventListener("touchmove", this.tm);
root.removeEventListener("touchend", this.te);
}
//call constructor
this.initialize(r, ip);
}
If your classnames are unique, the solution is rather simple. You can change the $ function to get by class name instead of by id:
var webkit_tools =
{
//$ function - simply a more robust getElementById
$:function(e)
{
if(typeof(e) == 'string')
{
return document.getElementsByClassName(e)[0];
// return document.getElementById(e);
}
return e;
},
... snipped ...
I've verified the above solution works (dragging and dropping) on my iPhone, but again, if the classnames are not unique, some added work will be in order based on the script's current implementation.
~~~EDIT~~~
In re-reading your request, you state that there will in fact NOT be unique classnames, hence the need for some sort of "bulk" drag/drop functionality. I've modified/extended the framework to support this. You can find the source for the modified version here:
https://gist.github.com/2474416
I had to change the API slightly. The dropabble API is unchanged, so passing a classname will simply add/remove the whole list of elements matching the classname passed. The clickable/draggable API was not so easy. To avoid a harsh rewrite, I updated the initialize methods for draggable/clickable to take an element ref rather than id or classname.
Correspondingly, I added a bulk_draggable(clazzname, options) and bulk_clickable(clazzname, options) function that basically iterates over the matched elements and calls the corresponding initializers. These functions return an array of draggables/clickables (one for each matched element).
Let me know if the "new" API is unclear. I did this rather quickly and lightly tested the happy paths, but can't invest and substantial amount of time rewriting the entire script.

Categories