Tartalomjegyzék

< JavaScript

Állapotok és kötések tárolása

Számláló

    <div id="app"></div>
    <script src="app.js"></script>   
app.js
const doc = {
    app: document.querySelector("#app"),
    button: document.createElement("button")
};
 
let state = { 
    count: 0 
};
 
window.addEventListener('load', () => {
    init();
})
 
function init() {    
    render();
    doc.button.addEventListener("click", () =>
      updateState()
    );
    doc.app.appendChild(doc.button);
}
 
function updateState() {
    state.count += 1
    render();
}
 
function render() {
    doc.button.innerText = `Count: ${state.count}`;
}

Háromszög területszámítás

index.html
<!DOCTYPE html>
<html lang="hu">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h3>Háromszög</h3>
 
    <div class="triangleForm">
        <div class="input">
            <label for="baseInput">Alap</label>
            <input type="text" id="baseInput">
        </div>
        <div class="input">
            <label for="heightInput">Magasság</label>
            <input type="text" id="heightInput">
        </div>
        <div>
            <button id="calcButton">Számít</button>
        </div>
        <div class="input">
            <label for="areaInput">Terület</label>
            <input type="text" id="areaInput">
        </div>
 
    </div>
 
    <script src="app.js"></script>
</body>
</html>
app.js
const doc = {
    baseInput: document.querySelector("#baseInput"),
    heightInput: document.querySelector("#heightInput"),
    areaInput: document.querySelector("#areaInput"),
    calcButton: document.querySelector("#calcButton")
}
const state = {
    base: 0,
    height: 0,
    area: 0
}
 
window.addEventListener('load', () => {
    init();
})
 
function init() {
    doc.calcButton.addEventListener("click", () => {
        startCalc();
    })
}
 
function startCalc() {
    state.base = doc.baseInput.value;
    state.height = doc.heightInput.value;
    state.area = calcArea(state.base, state.height);
    doc.areaInput.value = state.area;
}
 
function calcArea(base, height) {
    return base * height / 2;
}

Lásd még