Spaces:
Running
Running
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>ChemCalc - Chemical Equation Balancer & Calculator</title> | |
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"> | |
<style> | |
:root { | |
--primary: #4a6bdf; | |
--secondary: #6c757d; | |
--success: #28a745; | |
--danger: #dc3545; | |
--light: #f8f9fa; | |
--dark: #343a40; | |
--white: #ffffff; | |
--gray: #e9ecef; | |
} | |
* { | |
box-sizing: border-box; | |
margin: 0; | |
padding: 0; | |
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; | |
} | |
body { | |
background-color: #f5f7fa; | |
color: #333; | |
line-height: 1.6; | |
} | |
.container { | |
max-width: 1200px; | |
margin: 0 auto; | |
padding: 20px; | |
} | |
header { | |
text-align: center; | |
margin-bottom: 30px; | |
padding: 20px 0; | |
background: linear-gradient(135deg, var(--primary), #3a56c4); | |
color: white; | |
border-radius: 10px; | |
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); | |
} | |
h1 { | |
font-size: 2.5rem; | |
margin-bottom: 10px; | |
} | |
.subtitle { | |
font-size: 1.1rem; | |
opacity: 0.9; | |
} | |
.app-container { | |
display: grid; | |
grid-template-columns: 1fr; | |
gap: 30px; | |
} | |
@media (min-width: 992px) { | |
.app-container { | |
grid-template-columns: 1fr 1fr; | |
} | |
} | |
.card { | |
background-color: var(--white); | |
border-radius: 10px; | |
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); | |
padding: 25px; | |
transition: transform 0.3s ease; | |
} | |
.card:hover { | |
transform: translateY(-5px); | |
} | |
.card-title { | |
font-size: 1.5rem; | |
margin-bottom: 20px; | |
color: var(--primary); | |
display: flex; | |
align-items: center; | |
gap: 10px; | |
} | |
.card-title i { | |
font-size: 1.2rem; | |
} | |
.form-group { | |
margin-bottom: 20px; | |
} | |
label { | |
display: block; | |
margin-bottom: 8px; | |
font-weight: 600; | |
color: var(--dark); | |
} | |
input, select, textarea { | |
width: 100%; | |
padding: 12px 15px; | |
border: 1px solid var(--gray); | |
border-radius: 6px; | |
font-size: 1rem; | |
transition: border-color 0.3s; | |
} | |
input:focus, select:focus, textarea:focus { | |
outline: none; | |
border-color: var(--primary); | |
box-shadow: 0 0 0 3px rgba(74, 107, 223, 0.2); | |
} | |
.btn { | |
display: inline-block; | |
padding: 12px 20px; | |
background-color: var(--primary); | |
color: white; | |
border: none; | |
border-radius: 6px; | |
cursor: pointer; | |
font-size: 1rem; | |
font-weight: 600; | |
transition: all 0.3s; | |
text-align: center; | |
} | |
.btn:hover { | |
background-color: #3a56c4; | |
transform: translateY(-2px); | |
} | |
.btn-block { | |
display: block; | |
width: 100%; | |
} | |
.btn-secondary { | |
background-color: var(--secondary); | |
} | |
.btn-secondary:hover { | |
background-color: #5a6268; | |
} | |
.result-container { | |
margin-top: 20px; | |
padding: 20px; | |
background-color: var(--light); | |
border-radius: 6px; | |
border-left: 4px solid var(--primary); | |
} | |
.result-title { | |
font-weight: 600; | |
margin-bottom: 10px; | |
color: var(--dark); | |
} | |
.balanced-equation { | |
font-size: 1.2rem; | |
font-weight: 600; | |
color: var(--success); | |
margin: 15px 0; | |
padding: 10px; | |
background-color: rgba(40, 167, 69, 0.1); | |
border-radius: 5px; | |
text-align: center; | |
} | |
.error-message { | |
color: var(--danger); | |
margin-top: 10px; | |
font-weight: 500; | |
} | |
.calculation-results { | |
margin-top: 20px; | |
} | |
.calculation-item { | |
display: flex; | |
justify-content: space-between; | |
padding: 10px 0; | |
border-bottom: 1px solid var(--gray); | |
} | |
.calculation-item:last-child { | |
border-bottom: none; | |
} | |
.calculation-label { | |
font-weight: 600; | |
} | |
.calculation-value { | |
font-weight: 500; | |
color: var(--primary); | |
} | |
.periodic-hint { | |
font-size: 0.9rem; | |
color: var(--secondary); | |
margin-top: 5px; | |
} | |
.tabs { | |
display: flex; | |
margin-bottom: 20px; | |
border-bottom: 1px solid var(--gray); | |
} | |
.tab { | |
padding: 10px 20px; | |
cursor: pointer; | |
font-weight: 600; | |
color: var(--secondary); | |
border-bottom: 3px solid transparent; | |
transition: all 0.3s; | |
} | |
.tab.active { | |
color: var(--primary); | |
border-bottom: 3px solid var(--primary); | |
} | |
.tab-content { | |
display: none; | |
} | |
.tab-content.active { | |
display: block; | |
} | |
footer { | |
text-align: center; | |
margin-top: 50px; | |
padding: 20px; | |
color: var(--secondary); | |
font-size: 0.9rem; | |
} | |
.tooltip { | |
position: relative; | |
display: inline-block; | |
margin-left: 5px; | |
color: var(--secondary); | |
} | |
.tooltip .tooltiptext { | |
visibility: hidden; | |
width: 200px; | |
background-color: var(--dark); | |
color: var(--white); | |
text-align: center; | |
border-radius: 6px; | |
padding: 8px; | |
position: absolute; | |
z-index: 1; | |
bottom: 125%; | |
left: 50%; | |
transform: translateX(-50%); | |
opacity: 0; | |
transition: opacity 0.3s; | |
font-size: 0.8rem; | |
font-weight: normal; | |
} | |
.tooltip:hover .tooltiptext { | |
visibility: visible; | |
opacity: 1; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="container"> | |
<header> | |
<h1><i class="fas fa-atom"></i> ChemCalc</h1> | |
<p class="subtitle">Chemical Equation Balancer & Stoichiometry Calculator</p> | |
</header> | |
<div class="app-container"> | |
<!-- Equation Balancer Card --> | |
<div class="card"> | |
<h2 class="card-title"><i class="fas fa-balance-scale"></i> Equation Balancer</h2> | |
<div class="form-group"> | |
<label for="unbalanced-equation">Enter Chemical Equation:</label> | |
<input type="text" id="unbalanced-equation" placeholder="e.g. H2 + O2 = H2O"> | |
<p class="periodic-hint">Use standard notation (e.g. H2SO4, Ca(OH)2, NH4+)</p> | |
</div> | |
<button id="balance-btn" class="btn btn-block">Balance Equation</button> | |
<div id="balancer-result" class="result-container" style="display: none;"> | |
<p class="result-title">Balanced Equation:</p> | |
<div id="balanced-equation" class="balanced-equation"></div> | |
<div id="balancer-error" class="error-message"></div> | |
</div> | |
</div> | |
<!-- Stoichiometry Calculator Card --> | |
<div class="card"> | |
<h2 class="card-title"><i class="fas fa-calculator"></i> Stoichiometry Calculator</h2> | |
<div class="tabs"> | |
<div class="tab active" data-tab="mass">Mass</div> | |
<div class="tab" data-tab="moles">Moles</div> | |
<div class="tab" data-tab="volume">Volume</div> | |
<div class="tab" data-tab="concentration">Concentration</div> | |
</div> | |
<div class="tab-content active" id="mass-tab"> | |
<div class="form-group"> | |
<label for="stoich-equation">Chemical Equation:</label> | |
<input type="text" id="stoich-equation" placeholder="e.g. 2H2 + O2 = 2H2O"> | |
</div> | |
<div class="form-group"> | |
<label for="known-mass-compound">Known Compound:</label> | |
<input type="text" id="known-mass-compound" placeholder="e.g. H2"> | |
</div> | |
<div class="form-group"> | |
<label for="known-mass-value">Known Mass (g):</label> | |
<input type="number" id="known-mass-value" placeholder="e.g. 5.0"> | |
</div> | |
<div class="form-group"> | |
<label for="target-mass-compound">Target Compound:</label> | |
<input type="text" id="target-mass-compound" placeholder="e.g. H2O"> | |
</div> | |
<button id="calculate-mass-btn" class="btn btn-block">Calculate Mass</button> | |
</div> | |
<div class="tab-content" id="moles-tab"> | |
<div class="form-group"> | |
<label for="moles-equation">Chemical Equation:</label> | |
<input type="text" id="moles-equation" placeholder="e.g. 2H2 + O2 = 2H2O"> | |
</div> | |
<div class="form-group"> | |
<label for="known-moles-compound">Known Compound:</label> | |
<input type="text" id="known-moles-compound" placeholder="e.g. H2"> | |
</div> | |
<div class="form-group"> | |
<label for="known-moles-value">Known Moles:</label> | |
<input type="number" id="known-moles-value" placeholder="e.g. 2.5"> | |
</div> | |
<div class="form-group"> | |
<label for="target-moles-compound">Target Compound:</label> | |
<input type="text" id="target-moles-compound" placeholder="e.g. H2O"> | |
</div> | |
<button id="calculate-moles-btn" class="btn btn-block">Calculate Moles</button> | |
</div> | |
<div class="tab-content" id="volume-tab"> | |
<div class="form-group"> | |
<label for="volume-equation">Chemical Equation:</label> | |
<input type="text" id="volume-equation" placeholder="e.g. 2H2 + O2 = 2H2O"> | |
</div> | |
<div class="form-group"> | |
<label for="known-volume-compound">Known Gas Compound:</label> | |
<input type="text" id="known-volume-compound" placeholder="e.g. O2"> | |
</div> | |
<div class="form-group"> | |
<label for="known-volume-value">Known Volume (L):</label> | |
<input type="number" id="known-volume-value" placeholder="e.g. 10.0"> | |
</div> | |
<div class="form-group"> | |
<label for="target-volume-compound">Target Gas Compound:</label> | |
<input type="text" id="target-volume-compound" placeholder="e.g. H2"> | |
</div> | |
<div class="form-group"> | |
<label for="volume-temperature">Temperature (K):</label> | |
<input type="number" id="volume-temperature" placeholder="298" value="298"> | |
</div> | |
<div class="form-group"> | |
<label for="volume-pressure">Pressure (atm):</label> | |
<input type="number" id="volume-pressure" placeholder="1.0" value="1.0"> | |
</div> | |
<button id="calculate-volume-btn" class="btn btn-block">Calculate Volume</button> | |
</div> | |
<div class="tab-content" id="concentration-tab"> | |
<div class="form-group"> | |
<label for="conc-equation">Chemical Equation:</label> | |
<input type="text" id="conc-equation" placeholder="e.g. HCl + NaOH = NaCl + H2O"> | |
</div> | |
<div class="form-group"> | |
<label for="known-conc-compound">Known Solution Compound:</label> | |
<input type="text" id="known-conc-compound" placeholder="e.g. HCl"> | |
</div> | |
<div class="form-group"> | |
<label for="known-conc-value">Known Concentration (M):</label> | |
<input type="number" id="known-conc-value" placeholder="e.g. 0.1"> | |
</div> | |
<div class="form-group"> | |
<label for="known-conc-volume">Known Volume (L):</label> | |
<input type="number" id="known-conc-volume" placeholder="e.g. 0.025"> | |
</div> | |
<div class="form-group"> | |
<label for="target-conc-compound">Target Solution Compound:</label> | |
<input type="text" id="target-conc-compound" placeholder="e.g. NaOH"> | |
</div> | |
<div class="form-group"> | |
<label for="target-conc-volume">Target Volume (L):</label> | |
<input type="number" id="target-conc-volume" placeholder="e.g. 0.050"> | |
</div> | |
<button id="calculate-conc-btn" class="btn btn-block">Calculate Concentration</button> | |
</div> | |
<div id="stoich-result" class="result-container" style="display: none;"> | |
<p class="result-title">Calculation Results:</p> | |
<div id="stoich-error" class="error-message"></div> | |
<div id="calculation-results" class="calculation-results"></div> | |
</div> | |
</div> | |
<!-- Molar Mass Calculator Card --> | |
<div class="card"> | |
<h2 class="card-title"><i class="fas fa-weight-hanging"></i> Molar Mass Calculator</h2> | |
<div class="form-group"> | |
<label for="compound-formula">Chemical Formula:</label> | |
<input type="text" id="compound-formula" placeholder="e.g. C6H12O6"> | |
<p class="periodic-hint">Enter a single compound (e.g. H2SO4, Ca(OH)2, NH4+)</p> | |
</div> | |
<button id="calculate-molar-mass-btn" class="btn btn-block">Calculate Molar Mass</button> | |
<div id="molar-mass-result" class="result-container" style="display: none;"> | |
<p class="result-title">Molar Mass Calculation:</p> | |
<div id="molar-mass-error" class="error-message"></div> | |
<div id="molar-mass-results" class="calculation-results"></div> | |
</div> | |
</div> | |
<!-- Mole Calculator Card --> | |
<div class="card"> | |
<h2 class="card-title"><i class="fas fa-vial"></i> Mole Calculator</h2> | |
<div class="form-group"> | |
<label for="mole-compound">Chemical Formula:</label> | |
<input type="text" id="mole-compound" placeholder="e.g. NaCl"> | |
</div> | |
<div class="form-group"> | |
<label for="mole-value">Value:</label> | |
<input type="number" id="mole-value" placeholder="e.g. 5.0"> | |
</div> | |
<div class="form-group"> | |
<label for="mole-unit">From Unit:</label> | |
<select id="mole-unit"> | |
<option value="grams">Grams (g)</option> | |
<option value="moles">Moles (mol)</option> | |
<option value="molecules">Molecules</option> | |
<option value="liters">Liters (L) at STP</option> | |
</select> | |
</div> | |
<button id="calculate-mole-btn" class="btn btn-block">Convert</button> | |
<div id="mole-result" class="result-container" style="display: none;"> | |
<p class="result-title">Conversion Results:</p> | |
<div id="mole-error" class="error-message"></div> | |
<div id="mole-results" class="calculation-results"></div> | |
</div> | |
</div> | |
</div> | |
<footer> | |
<p>ChemCalc © 2023 | A comprehensive chemical equation and stoichiometry calculator</p> | |
</footer> | |
</div> | |
<script> | |
// Periodic table data (simplified) | |
const periodicTable = { | |
"H": { name: "Hydrogen", mass: 1.008 }, | |
"He": { name: "Helium", mass: 4.0026 }, | |
"Li": { name: "Lithium", mass: 6.94 }, | |
"Be": { name: "Beryllium", mass: 9.0122 }, | |
"B": { name: "Boron", mass: 10.81 }, | |
"C": { name: "Carbon", mass: 12.011 }, | |
"N": { name: "Nitrogen", mass: 14.007 }, | |
"O": { name: "Oxygen", mass: 15.999 }, | |
"F": { name: "Fluorine", mass: 18.998 }, | |
"Ne": { name: "Neon", mass: 20.180 }, | |
"Na": { name: "Sodium", mass: 22.990 }, | |
"Mg": { name: "Magnesium", mass: 24.305 }, | |
"Al": { name: "Aluminum", mass: 26.982 }, | |
"Si": { name: "Silicon", mass: 28.085 }, | |
"P": { name: "Phosphorus", mass: 30.974 }, | |
"S": { name: "Sulfur", mass: 32.06 }, | |
"Cl": { name: "Chlorine", mass: 35.45 }, | |
"Ar": { name: "Argon", mass: 39.948 }, | |
"K": { name: "Potassium", mass: 39.098 }, | |
"Ca": { name: "Calcium", mass: 40.078 }, | |
"Sc": { name: "Scandium", mass: 44.956 }, | |
"Ti": { name: "Titanium", mass: 47.867 }, | |
"V": { name: "Vanadium", mass: 50.942 }, | |
"Cr": { name: "Chromium", mass: 51.996 }, | |
"Mn": { name: "Manganese", mass: 54.938 }, | |
"Fe": { name: "Iron", mass: 55.845 }, | |
"Co": { name: "Cobalt", mass: 58.933 }, | |
"Ni": { name: "Nickel", mass: 58.693 }, | |
"Cu": { name: "Copper", mass: 63.546 }, | |
"Zn": { name: "Zinc", mass: 65.38 }, | |
"Ga": { name: "Gallium", mass: 69.723 }, | |
"Ge": { name: "Germanium", mass: 72.630 }, | |
"As": { name: "Arsenic", mass: 74.922 }, | |
"Se": { name: "Selenium", mass: 78.971 }, | |
"Br": { name: "Bromine", mass: 79.904 }, | |
"Kr": { name: "Krypton", mass: 83.798 }, | |
"Rb": { name: "Rubidium", mass: 85.468 }, | |
"Sr": { name: "Strontium", mass: 87.62 }, | |
"Y": { name: "Yttrium", mass: 88.906 }, | |
"Zr": { name: "Zirconium", mass: 91.224 }, | |
"Nb": { name: "Niobium", mass: 92.906 }, | |
"Mo": { name: "Molybdenum", mass: 95.95 }, | |
"Tc": { name: "Technetium", mass: 98.0 }, | |
"Ru": { name: "Ruthenium", mass: 101.07 }, | |
"Rh": { name: "Rhodium", mass: 102.91 }, | |
"Pd": { name: "Palladium", mass: 106.42 }, | |
"Ag": { name: "Silver", mass: 107.87 }, | |
"Cd": { name: "Cadmium", mass: 112.41 }, | |
"In": { name: "Indium", mass: 114.82 }, | |
"Sn": { name: "Tin", mass: 118.71 }, | |
"Sb": { name: "Antimony", mass: 121.76 }, | |
"Te": { name: "Tellurium", mass: 127.60 }, | |
"I": { name: "Iodine", mass: 126.90 }, | |
"Xe": { name: "Xenon", mass: 131.29 }, | |
"Cs": { name: "Cesium", mass: 132.91 }, | |
"Ba": { name: "Barium", mass: 137.33 }, | |
"La": { name: "Lanthanum", mass: 138.91 }, | |
"Ce": { name: "Cerium", mass: 140.12 }, | |
"Pr": { name: "Praseodymium", mass: 140.91 }, | |
"Nd": { name: "Neodymium", mass: 144.24 }, | |
"Pm": { name: "Promethium", mass: 145.0 }, | |
"Sm": { name: "Samarium", mass: 150.36 }, | |
"Eu": { name: "Europium", mass: 151.96 }, | |
"Gd": { name: "Gadolinium", mass: 157.25 }, | |
"Tb": { name: "Terbium", mass: 158.93 }, | |
"Dy": { name: "Dysprosium", mass: 162.50 }, | |
"Ho": { name: "Holmium", mass: 164.93 }, | |
"Er": { name: "Erbium", mass: 167.26 }, | |
"Tm": { name: "Thulium", mass: 168.93 }, | |
"Yb": { name: "Ytterbium", mass: 173.05 }, | |
"Lu": { name: "Lutetium", mass: 174.97 }, | |
"Hf": { name: "Hafnium", mass: 178.49 }, | |
"Ta": { name: "Tantalum", mass: 180.95 }, | |
"W": { name: "Tungsten", mass: 183.84 }, | |
"Re": { name: "Rhenium", mass: 186.21 }, | |
"Os": { name: "Osmium", mass: 190.23 }, | |
"Ir": { name: "Iridium", mass: 192.22 }, | |
"Pt": { name: "Platinum", mass: 195.08 }, | |
"Au": { name: "Gold", mass: 196.97 }, | |
"Hg": { name: "Mercury", mass: 200.59 }, | |
"Tl": { name: "Thallium", mass: 204.38 }, | |
"Pb": { name: "Lead", mass: 207.2 }, | |
"Bi": { name: "Bismuth", mass: 208.98 }, | |
"Po": { name: "Polonium", mass: 209.0 }, | |
"At": { name: "Astatine", mass: 210.0 }, | |
"Rn": { name: "Radon", mass: 222.0 }, | |
"Fr": { name: "Francium", mass: 223.0 }, | |
"Ra": { name: "Radium", mass: 226.0 }, | |
"Ac": { name: "Actinium", mass: 227.0 }, | |
"Th": { name: "Thorium", mass: 232.04 }, | |
"Pa": { name: "Protactinium", mass: 231.04 }, | |
"U": { name: "Uranium", mass: 238.03 }, | |
"Np": { name: "Neptunium", mass: 237.0 }, | |
"Pu": { name: "Plutonium", mass: 244.0 }, | |
"Am": { name: "Americium", mass: 243.0 }, | |
"Cm": { name: "Curium", mass: 247.0 }, | |
"Bk": { name: "Berkelium", mass: 247.0 }, | |
"Cf": { name: "Californium", mass: 251.0 }, | |
"Es": { name: "Einsteinium", mass: 252.0 }, | |
"Fm": { name: "Fermium", mass: 257.0 }, | |
"Md": { name: "Mendelevium", mass: 258.0 }, | |
"No": { name: "Nobelium", mass: 259.0 }, | |
"Lr": { name: "Lawrencium", mass: 262.0 }, | |
"Rf": { name: "Rutherfordium", mass: 267.0 }, | |
"Db": { name: "Dubnium", mass: 270.0 }, | |
"Sg": { name: "Seaborgium", mass: 271.0 }, | |
"Bh": { name: "Bohrium", mass: 270.0 }, | |
"Hs": { name: "Hassium", mass: 277.0 }, | |
"Mt": { name: "Meitnerium", mass: 276.0 }, | |
"Ds": { name: "Darmstadtium", mass: 281.0 }, | |
"Rg": { name: "Roentgenium", mass: 280.0 }, | |
"Cn": { name: "Copernicium", mass: 285.0 }, | |
"Nh": { name: "Nihonium", mass: 286.0 }, | |
"Fl": { name: "Flerovium", mass: 289.0 }, | |
"Mc": { name: "Moscovium", mass: 290.0 }, | |
"Lv": { name: "Livermorium", mass: 293.0 }, | |
"Ts": { name: "Tennessine", mass: 294.0 }, | |
"Og": { name: "Oganesson", mass: 294.0 } | |
}; | |
// Tab functionality | |
document.querySelectorAll('.tab').forEach(tab => { | |
tab.addEventListener('click', () => { | |
// Remove active class from all tabs and contents | |
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active')); | |
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active')); | |
// Add active class to clicked tab and corresponding content | |
tab.classList.add('active'); | |
const tabId = tab.getAttribute('data-tab'); | |
document.getElementById(`${tabId}-tab`).classList.add('active'); | |
}); | |
}); | |
// Helper function to parse chemical formulas | |
function parseFormula(formula) { | |
const elements = {}; | |
let currentElement = ''; | |
let currentCount = ''; | |
let inParenthesis = false; | |
let parenthesisContent = ''; | |
let parenthesisMultiplier = ''; | |
for (let i = 0; i < formula.length; i++) { | |
const char = formula[i]; | |
// Handle uppercase letters (start of new element) | |
if (char === char.toUpperCase() && char !== char.toLowerCase()) { | |
if (currentElement) { | |
const count = currentCount ? parseInt(currentCount) : 1; | |
if (periodicTable[currentElement]) { | |
elements[currentElement] = (elements[currentElement] || 0) + count; | |
} else { | |
return { error: `Unknown element: ${currentElement}` }; | |
} | |
} | |
currentElement = char; | |
currentCount = ''; | |
} | |
// Handle lowercase letters (part of element symbol) | |
else if (char === char.toLowerCase() && char !== char.toUpperCase()) { | |
currentElement += char; | |
} | |
// Handle digits (count of element) | |
else if (!isNaN(char)) { | |
currentCount += char; | |
} | |
// Handle opening parenthesis | |
else if (char === '(') { | |
if (currentElement) { | |
const count = currentCount ? parseInt(currentCount) : 1; | |
if (periodicTable[currentElement]) { | |
elements[currentElement] = (elements[currentElement] || 0) + count; | |
} else { | |
return { error: `Unknown element: ${currentElement}` }; | |
} | |
} | |
currentElement = ''; | |
currentCount = ''; | |
inParenthesis = true; | |
parenthesisContent = ''; | |
parenthesisMultiplier = ''; | |
} | |
// Handle closing parenthesis | |
else if (char === ')') { | |
inParenthesis = false; | |
i++; // Skip to next character to check for multiplier | |
// Get the multiplier after parenthesis | |
while (i < formula.length && !isNaN(formula[i])) { | |
parenthesisMultiplier += formula[i]; | |
i++; | |
} | |
i--; // Adjust index since we'll increment in next loop iteration | |
const subElements = parseFormula(parenthesisContent); | |
if (subElements.error) return subElements; | |
const multiplier = parenthesisMultiplier ? parseInt(parenthesisMultiplier) : 1; | |
for (const el in subElements) { | |
elements[el] = (elements[el] || 0) + (subElements[el] * multiplier); | |
} | |
} | |
// Handle content inside parenthesis | |
else if (inParenthesis) { | |
parenthesisContent += char; | |
} | |
} | |
// Add the last element | |
if (currentElement) { | |
const count = currentCount ? parseInt(currentCount) : 1; | |
if (periodicTable[currentElement]) { | |
elements[currentElement] = (elements[currentElement] || 0) + count; | |
} else { | |
return { error: `Unknown element: ${currentElement}` }; | |
} | |
} | |
return elements; | |
} | |
// Helper function to calculate molar mass | |
function calculateMolarMass(formula) { | |
const elements = parseFormula(formula); | |
if (elements.error) return elements; | |
let molarMass = 0; | |
for (const el in elements) { | |
molarMass += periodicTable[el].mass * elements[el]; | |
} | |
return { | |
molarMass: molarMass, | |
elements: elements | |
}; | |
} | |
// Helper function to parse chemical equation | |
function parseEquation(equation) { | |
// Split into reactants and products | |
const sides = equation.split('=').map(s => s.trim()); | |
if (sides.length !== 2) { | |
return { error: "Equation must have exactly one '=' sign" }; | |
} | |
const reactants = sides[0].split('+').map(s => s.trim()); | |
const products = sides[1].split('+').map(s => s.trim()); | |
// Parse all compounds | |
const allCompounds = [...reactants, ...products]; | |
const parsedCompounds = []; | |
for (const compound of allCompounds) { | |
// Extract coefficient if present | |
let coefficient = 1; | |
let formula = compound; | |
const coefficientMatch = compound.match(/^(\d+)/); | |
if (coefficientMatch) { | |
coefficient = parseInt(coefficientMatch[1]); | |
formula = compound.slice(coefficientMatch[0].length).trim(); | |
} | |
const molarMassResult = calculateMolarMass(formula); | |
if (molarMassResult.error) { | |
return { error: molarMassResult.error }; | |
} | |
parsedCompounds.push({ | |
formula: formula, | |
coefficient: coefficient, | |
molarMass: molarMassResult.molarMass, | |
elements: molarMassResult.elements | |
}); | |
} | |
return { | |
reactants: parsedCompounds.slice(0, reactants.length), | |
products: parsedCompounds.slice(reactants.length), | |
allElements: getAllElements(parsedCompounds) | |
}; | |
} | |
// Helper function to get all unique elements in equation | |
function getAllElements(compounds) { | |
const elements = new Set(); | |
for (const compound of compounds) { | |
for (const el in compound.elements) { | |
elements.add(el); | |
} | |
} | |
return Array.from(elements); | |
} | |
// Helper function to balance equation (simplified algorithm) | |
function balanceEquation(equation) { | |
const parsed = parseEquation(equation); | |
if (parsed.error) return parsed; | |
// This is a simplified balancing algorithm | |
// In a real application, you would implement a more robust matrix-based approach | |
const { reactants, products } = parsed; | |
// Count total atoms per element on each side | |
const elementCounts = {}; | |
for (const el of parsed.allElements) { | |
elementCounts[el] = { reactant: 0, product: 0 }; | |
} | |
for (const compound of reactants) { | |
for (const el in compound.elements) { | |
elementCounts[el].reactant += compound.coefficient * compound.elements[el]; | |
} | |
} | |
for (const compound of products) { | |
for (const el in compound.elements) { | |
elementCounts[el].product += compound.coefficient * compound.elements[el]; | |
} | |
} | |
// Check if already balanced | |
let isBalanced = true; | |
for (const el in elementCounts) { | |
if (elementCounts[el].reactant !== elementCounts[el].product) { | |
isBalanced = false; | |
break; | |
} | |
} | |
if (isBalanced) { | |
return { | |
balancedEquation: equation, | |
coefficients: { | |
reactants: reactants.map(c => c.coefficient), | |
products: products.map(c => c.coefficient) | |
} | |
}; | |
} | |
// Try to balance simple equations (this is very simplified) | |
if (reactants.length === 2 && products.length === 1) { | |
// A + B = AB type | |
const newCoefficients = { | |
reactants: [1, 1], | |
products: [1] | |
}; | |
// Verify balance | |
let balanced = true; | |
for (const el in elementCounts) { | |
const left = newCoefficients.reactants[0] * (reactants[0].elements[el] || 0) + | |
newCoefficients.reactants[1] * (reactants[1].elements[el] || 0); | |
const right = newCoefficients.products[0] * (products[0].elements[el] || 0); | |
if (left !== right) { | |
balanced = false; | |
break; | |
} | |
} | |
if (balanced) { | |
const balancedEq = `${newCoefficients.reactants[0]}${reactants[0].formula} + ${newCoefficients.reactants[1]}${reactants[1].formula} = ${newCoefficients.products[0]}${products[0].formula}`; | |
return { | |
balancedEquation: balancedEq, | |
coefficients: newCoefficients | |
}; | |
} | |
} | |
// If we can't balance it with simple rules, return an error | |
return { error: "Unable to balance this equation automatically. Try a simpler equation or balance manually." }; | |
} | |
// Helper function to perform stoichiometry calculation | |
function performStoichiometry(equation, knownCompound, knownValue, targetCompound, calculationType) { | |
const parsed = parseEquation(equation); | |
if (parsed.error) return parsed; | |
// Find known and target compounds | |
const allCompounds = [...parsed.reactants, ...parsed.products]; | |
const known = allCompounds.find(c => c.formula === knownCompound); | |
const target = allCompounds.find(c => c.formula === targetCompound); | |
if (!known) return { error: `Compound ${knownCompound} not found in equation` }; | |
if (!target) return { error: `Compound ${targetCompound} not found in equation` }; | |
// Calculate moles of known compound | |
let knownMoles; | |
if (calculationType === 'mass') { | |
knownMoles = knownValue / known.molarMass; | |
} else if (calculationType === 'moles') { | |
knownMoles = knownValue; | |
} else if (calculationType === 'volume') { | |
// Using ideal gas law: PV = nRT => n = PV/RT | |
const pressure = parseFloat(document.getElementById('volume-pressure').value) || 1.0; | |
const temperature = parseFloat(document.getElementById('volume-temperature').value) || 298; | |
const R = 0.0821; // L·atm/(K·mol) | |
knownMoles = (pressure * knownValue) / (R * temperature); | |
} else if (calculationType === 'concentration') { | |
const volume = parseFloat(document.getElementById('known-conc-volume').value); | |
if (!volume) return { error: "Known volume is required for concentration calculations" }; | |
knownMoles = knownValue * volume; | |
} | |
// Calculate moles of target compound using stoichiometric ratios | |
const targetMoles = knownMoles * (target.coefficient / known.coefficient); | |
// Calculate final value based on calculation type | |
let resultValue; | |
if (calculationType === 'mass') { | |
resultValue = targetMoles * target.molarMass; | |
} else if (calculationType === 'moles') { | |
resultValue = targetMoles; | |
} else if (calculationType === 'volume') { | |
// Using ideal gas law: V = nRT/P | |
const pressure = parseFloat(document.getElementById('volume-pressure').value) || 1.0; | |
const temperature = parseFloat(document.getElementById('volume-temperature').value) || 298; | |
const R = 0.0821; // L·atm/(K·mol) | |
resultValue = (targetMoles * R * temperature) / pressure; | |
} else if (calculationType === 'concentration') { | |
const volume = parseFloat(document.getElementById('target-conc-volume').value); | |
if (!volume) return { error: "Target volume is required for concentration calculations" }; | |
resultValue = targetMoles / volume; | |
} | |
return { | |
knownMoles: knownMoles, | |
targetMoles: targetMoles, | |
resultValue: resultValue, | |
calculationType: calculationType, | |
knownCompound: knownCompound, | |
targetCompound: targetCompound | |
}; | |
} | |
// Helper function to perform mole conversions | |
function performMoleConversion(compound, value, fromUnit, toUnits = ['grams', 'moles', 'molecules', 'liters']) { | |
const molarMassResult = calculateMolarMass(compound); | |
if (molarMassResult.error) return molarMassResult; | |
const molarMass = molarMassResult.molarMass; | |
const AVOGADRO = 6.022e23; | |
const STP_VOLUME = 22.4; // L/mol at STP | |
// Convert input value to moles first | |
let moles; | |
switch (fromUnit) { | |
case 'grams': | |
moles = value / molarMass; | |
break; | |
case 'moles': | |
moles = value; | |
break; | |
case 'molecules': | |
moles = value / AVOGADRO; | |
break; | |
case 'liters': | |
moles = value / STP_VOLUME; | |
break; | |
default: | |
return { error: "Invalid unit" }; | |
} | |
// Convert moles to all other units | |
const results = {}; | |
for (const unit of toUnits) { | |
switch (unit) { | |
case 'grams': | |
results.grams = moles * molarMass; | |
break; | |
case 'moles': | |
results.moles = moles; | |
break; | |
case 'molecules': | |
results.molecules = moles * AVOGADRO; | |
break; | |
case 'liters': | |
results.liters = moles * STP_VOLUME; | |
break; | |
} | |
} | |
return { | |
compound: compound, | |
molarMass: molarMass, | |
initialValue: value, | |
initialUnit: fromUnit, | |
moles: moles, | |
results: results | |
}; | |
} | |
// Function to display stoichiometry results | |
function displayStoichResult(result) { | |
const resultContainer = document.getElementById('stoich-result'); | |
resultContainer.style.display = 'block'; | |
if (result.error) { | |
showStoichError(result.error); | |
document.getElementById('calculation-results').innerHTML = ''; | |
return; | |
} | |
document.getElementById('stoich-error').textContent = ''; | |
let html = ''; | |
let resultUnit = ''; | |
switch (result.calculationType) { | |
case 'mass': | |
resultUnit = 'g'; | |
html = ` | |
<div class="calculation-item"> | |
<span class="calculation-label">Moles of ${result.knownCompound}:</span> | |
<span class="calculation-value">${result.knownMoles.toExponential(4)} mol</span> | |
</div> | |
<div class="calculation-item"> | |
<span class="calculation-label">Moles of ${result.targetCompound}:</span> | |
<span class="calculation-value">${result.targetMoles.toExponential(4)} mol</span> | |
</div> | |
<div class="calculation-item"> | |
<span class="calculation-label">Mass of ${result.targetCompound}:</span> | |
<span class="calculation-value">${result.resultValue.toFixed(4)} ${resultUnit}</span> | |
</div> | |
`; | |
break; | |
case 'moles': | |
resultUnit = 'mol'; | |
html = ` | |
<div class="calculation-item"> | |
<span class="calculation-label">Moles of ${result.targetCompound}:</span> | |
<span class="calculation-value">${result.resultValue.toExponential(4)} ${resultUnit}</span> | |
</div> | |
`; | |
break; | |
case 'volume': | |
resultUnit = 'L'; | |
html = ` | |
<div class="calculation-item"> | |
<span class="calculation-label">Moles of ${result.knownCompound}:</span> | |
<span class="calculation-value">${result.knownMoles.toExponential(4)} mol</span> | |
</div> | |
<div class="calculation-item"> | |
<span class="calculation-label">Moles of ${result.targetCompound}:</span> | |
<span class="calculation-value">${result.targetMoles.toExponential(4)} mol</span> | |
</div> | |
<div class="calculation-item"> | |
<span class="calculation-label">Volume of ${result.targetCompound}:</span> | |
<span class="calculation-value">${result.resultValue.toFixed(4)} ${resultUnit}</span> | |
</div> | |
`; | |
break; | |
case 'concentration': | |
resultUnit = 'M'; | |
html = ` | |
<div class="calculation-item"> | |
<span class="calculation-label">Moles of ${result.knownCompound}:</span> | |
<span class="calculation-value">${result.knownMoles.toExponential(4)} mol</span> | |
</div> | |
<div class="calculation-item"> | |
<span class="calculation-label">Moles of ${result.targetCompound}:</span> | |
<span class="calculation-value">${result.targetMoles.toExponential(4)} mol</span> | |
</div> | |
<div class="calculation-item"> | |
<span class="calculation-label">Concentration of ${result.targetCompound}:</span> | |
<span class="calculation-value">${result.resultValue.toFixed(4)} ${resultUnit}</span> | |
</div> | |
`; | |
break; | |
} | |
document.getElementById('calculation-results').innerHTML = html; | |
} | |
// Function to show stoichiometry error | |
function showStoichError(message) { | |
document.getElementById('stoich-error').textContent = message; | |
document.getElementById('stoich-result').style.display = 'block'; | |
document.getElementById('calculation-results').innerHTML = ''; | |
} | |
// Function to show molar mass error | |
function showMolarMassError(message) { | |
document.getElementById('molar-mass-error').textContent = message; | |
} | |
// Function to show mole conversion error | |
function showMoleError(message) { | |
document.getElementById('mole-error').textContent = message; | |
} | |
// Event listeners | |
document.getElementById('balance-btn').addEventListener('click', () => { | |
const equation = document.getElementById('unbalanced-equation').value.trim(); | |
if (!equation) { | |
document.getElementById('balancer-error').textContent = "Please enter an equation to balance"; | |
document.getElementById('balancer-result').style.display = 'block'; | |
return; | |
} | |
const result = balanceEquation(equation); | |
const resultContainer = document.getElementById('balancer-result'); | |
resultContainer.style.display = 'block'; | |
if (result.error) { | |
document.getElementById('balancer-error').textContent = result.error; | |
document.getElementById('balanced-equation').textContent = ''; | |
} else { | |
document.getElementById('balancer-error').textContent = ''; | |
document.getElementById('balanced-equation').textContent = result.balancedEquation; | |
} | |
}); | |
// Mass calculation | |
document.getElementById('calculate-mass-btn').addEventListener('click', () => { | |
const equation = document.getElementById('stoich-equation').value.trim(); | |
const knownCompound = document.getElementById('known-mass-compound').value.trim(); | |
const knownValue = parseFloat(document.getElementById('known-mass-value').value); | |
const targetCompound = document.getElementById('target-mass-compound').value.trim(); | |
if (!equation || !knownCompound || isNaN(knownValue) || !targetCompound) { | |
showStoichError("Please fill in all fields with valid values"); | |
return; | |
} | |
const result = performStoichiometry(equation, knownCompound, knownValue, targetCompound, 'mass'); | |
displayStoichResult(result); | |
}); | |
// Moles calculation | |
document.getElementById('calculate-moles-btn').addEventListener('click', () => { | |
const equation = document.getElementById('moles-equation').value.trim(); | |
const knownCompound = document.getElementById('known-moles-compound').value.trim(); | |
const knownValue = parseFloat(document.getElementById('known-moles-value').value); | |
const targetCompound = document.getElementById('target-moles-compound').value.trim(); | |
if (!equation || !knownCompound || isNaN(knownValue) || !targetCompound) { | |
showStoichError("Please fill in all fields with valid values"); | |
return; | |
} | |
const result = performStoichiometry(equation, knownCompound, knownValue, targetCompound, 'moles'); | |
displayStoichResult(result); | |
}); | |
// Volume calculation | |
document.getElementById('calculate-volume-btn').addEventListener('click', () => { | |
const equation = document.getElementById('volume-equation').value.trim(); | |
const knownCompound = document.getElementById('known-volume-compound').value.trim(); | |
const knownValue = parseFloat(document.getElementById('known-volume-value').value); | |
const targetCompound = document.getElementById('target-volume-compound').value.trim(); | |
if (!equation || !knownCompound || isNaN(knownValue) || !targetCompound) { | |
showStoichError("Please fill in all fields with valid values"); | |
return; | |
} | |
const result = performStoichiometry(equation, knownCompound, knownValue, targetCompound, 'volume'); | |
displayStoichResult(result); | |
}); | |
// Concentration calculation | |
document.getElementById('calculate-conc-btn').addEventListener('click', () => { | |
const equation = document.getElementById('conc-equation').value.trim(); | |
const knownCompound = document.getElementById('known-conc-compound').value.trim(); | |
const knownValue = parseFloat(document.getElementById('known-conc-value').value); | |
const targetCompound = document.getElementById('target-conc-compound').value.trim(); | |
if (!equation || !knownCompound || isNaN(knownValue) || !targetCompound) { | |
showStoichError("Please fill in all fields with valid values"); | |
return; | |
} | |
const result = performStoichiometry(equation, knownCompound, knownValue, targetCompound, 'concentration'); | |
displayStoichResult(result); | |
}); | |
// Molar mass calculation | |
document.getElementById('calculate-molar-mass-btn').addEventListener('click', () => { | |
const formula = document.getElementById('compound-formula').value.trim(); | |
if (!formula) { | |
showMolarMassError("Please enter a chemical formula"); | |
return; | |
} | |
const result = calculateMolarMass(formula); | |
const resultContainer = document.getElementById('molar-mass-result'); | |
resultContainer.style.display = 'block'; | |
if (result.error) { | |
showMolarMassError(result.error); | |
document.getElementById('molar-mass-results').innerHTML = ''; | |
} else { | |
document.getElementById('molar-mass-error').textContent = ''; | |
let html = ` | |
<div class="calculation-item"> | |
<span class="calculation-label">Molar Mass:</span> | |
<span class="calculation-value">${result.molarMass.toFixed(4)} g/mol</span> | |
</div> | |
<div class="calculation-item"> | |
<span class="calculation-label">Composition:</span> | |
<span class="calculation-value"></span> | |
</div> | |
`; | |
for (const el in result.elements) { | |
html += ` | |
<div class="calculation-item" style="padding-left: 20px;"> | |
<span class="calculation-label">${el} (${periodicTable[el].name}):</span> | |
<span class="calculation-value">${result.elements[el]} atom(s) × ${periodicTable[el].mass.toFixed(4)} g/mol = ${(result.elements[el] * periodicTable[el].mass).toFixed(4)} g/mol</span> | |
</div> | |
`; | |
} | |
document.getElementById('molar-mass-results').innerHTML = html; | |
} | |
}); | |
// Mole conversion calculation | |
document.getElementById('calculate-mole-btn').addEventListener('click', () => { | |
const compound = document.getElementById('mole-compound').value.trim(); | |
const value = parseFloat(document.getElementById('mole-value').value); | |
const fromUnit = document.getElementById('mole-unit').value; | |
if (!compound || isNaN(value)) { | |
showMoleError("Please enter a valid compound and value"); | |
return; | |
} | |
const result = performMoleConversion(compound, value, fromUnit); | |
const resultContainer = document.getElementById('mole-result'); | |
resultContainer.style.display = 'block'; | |
if (result.error) { | |
showMoleError(result.error); | |
document.getElementById('mole-results').innerHTML = ''; | |
} else { | |
document.getElementById('mole-error').textContent = ''; | |
let html = ` | |
<div class="calculation-item"> | |
<span class="calculation-label">Molar Mass:</span> | |
<span class="calculation-value">${result.molarMass.toFixed(4)} g/mol</span> | |
</div> | |
<div class="calculation-item"> | |
<span class="calculation-label">Initial Value:</span> | |
<span class="calculation-value">${value} ${fromUnit}</span> | |
</div> | |
<div class="calculation-item"> | |
<span class="calculation-label">Moles:</span> | |
<span class="calculation-value">${result.moles.toExponential(4)} mol</span> | |
</div> | |
`; | |
if (fromUnit !== 'grams') { | |
html += ` | |
<div class="calculation-item"> | |
<span class="calculation-label">Mass:</span> | |
<span class="calculation-value">${result.results.grams.toExponential(4)} g</span> | |
</div> | |
`; | |
} | |
if (fromUnit !== 'moles') { | |
html += ` | |
<div class="calculation-item"> | |
<span class="calculation-label">Moles:</span> | |
<span class="calculation-value">${result.moles.toExponential(4)} mol</span> | |
</div> | |
`; | |
} | |
if (fromUnit !== 'molecules') { | |
html += ` | |
<div class="calculation-item"> | |
<span class="calculation-label">Molecules:</span> | |
<span class="calculation-value">${result.results.molecules.toExponential(4)}</span> | |
</div> | |
`; | |
} | |
if (fromUnit !== 'liters') { | |
html += ` | |
<div class="calculation-item"> | |
<span class="calculation-label">Volume at STP:</span> | |
<span class="calculation-value">${result.results.liters.toExponential(4)} L</span> | |
</div> | |
`; | |
} | |
document.getElementById('mole-results').innerHTML = html; | |
} | |
}); | |
</script> | |
</body> | |
</html> |