Skip to content
This is my space, where experience meets the will to start over. This is my space, where experience meets the will to start over.

The first step is knowing where you want to go.

  • Home
  • Coding Hub
    • Software & Project
      • Small Biz Ops – S.B.O.
        • SmallBizOps – Day 10/90
      • CRM/ERP
      • MyTracker
      • My Budget
    • Form Zero to “WoW”
      • JavaScript from Zero (Completed)
        • 2. Remove and Edit List Items
        • 3. Separate HTML and JavaScript, Use addEventListener and Conditional Logic
        • 4. Add Dynamic CSS Classes
        • 5. Save & Restore Your List with localStorage
        • 6 – Turn Your App into a Full To-Do List
      • Python from Zero (Completed)
        • 2. Lists & Loops
        • 3. Conditional Menus
        • 4. Edit & Remove Tasks (with closing: Python vs PHP and Large Data)
        • 5 – Save to File: Make Your Tasks Survive Restarts
        • 6 — Pythin from zero – Final Project Polishing: Numbering, Formatting, and Preparing for CSV
      • Rust – From Zero to “WoW” (Completed)
        • 1 – Setup and Project Structure in Rust
        • 2 – User input: validation and error handling
        • 3 – Rust from Zero to “WoW – BMI Calculation and Conditional Logic
        • 4 –Rust – Clear, Formatted Output
        • 5 – Rust – Final Thoughts: Precision as a Form of Respect
      • Go from Zero to “WoW” (Completed)
        • 1 – Why Go Is Perfect for a Personal Expense Tracker
        • 2 – Logging Expenses and Console Input
        • 3 – Go from Zero to “WoW” – Smart Filtering & Display Logic
        • 4 – Go – Saving Data to Local Files
        • 5 – Go – Final Project – Expense Tracker in Go
      • C++ from Zero to “WoW” (Completed)
        • 1 – Why C++ for file organization?
        • 2 – C++ – File Type Detection and Classification
        • 3 – C++ – Creating & Managing Subfolders
        • 4 – C++ – Safe File Movement and User Feedback
        • 5 – C++ – Order as Mental Clarity
      • Ubuntu – From Zero to “WoW” (Completed)
        • 2 – Ubuntu – The Desktop Environment and Essential Commands
        • 3 – Ubuntu – Managing Files, Folders, and Permissions
        • 4 – Ubuntu – Installing and Updating Software with APT and Snap
        • 5 – Ubuntu – Customizing the Desktop Environment
        • 6 – Ubuntu – Network and Device Configuration
        • 7 – Ubuntu – User Management & System Security — “The Cathedral of Permissions”
        • 8 – Ubuntu – The Talking Machine: Terminal & Bash Scripting
        • 9 – Ubuntu – Ubuntu as a Server or Development Environment
        • 10 – Ubuntu – Backup, Maintenance & Troubleshooting
    • Git Hub Repository
      • Small Biz Ops – S.B.O.
      • Mini ERP – PHP & MySQL
      • CleverCRM (Java, Spring Boot)
      • FraudWatch (Python, FastAPI + scikit-learn)
      • OnboardIQ – Smart Onboarding Portal (Flask + SQLite Demo)
    • ArchPilot
      • 1-Users & Roles, End-to-End (Architecture, Database, and Cross-Framework Code)
      • 2 – Client Registry (CRM) Across Frameworks
      • 3 – Project & Budget Tracker (ERP)
      • 4 – Approval Workflow Engine Multi-step routing, status tracking, escalation paths
      • 5 – Audit Trail & Versioning
    • Small Biz Ops – S.B.O.
  • Vivere in USA
  • P4Y
  • Testi poetici
    • 1 – Sospeso
    • 2 – Il bicchiere di vetro quieto
    • 3 – Quando l’amore inciampa
    • 4 – Ma chi siete davvero?
    • 5 – Above the Thread of Day
    • 6 – The Truth That Doesn’t Exist
    • 7 – All of You, I Miss
    • 8 – The Captain and the Ocean
    • 9 – Between Light and Mist
    • 10 – Il peso delle scelte
  • Contact
  • Admin
This is my space, where experience meets the will to start over.
This is my space, where experience meets the will to start over.

The first step is knowing where you want to go.

Coding – Step 9.3 – JavaScript from Scratch: Separate HTML and JavaScript, Use addEventListener and Conditional Logic

Posted on 26 Luglio 20259 Agosto 2025 By Francesco

In the previous level of our Shopping List project, we built a simple app that allowed us to add and remove items dynamically. However, all the JavaScript code was still mixed inside the HTML, using inline onclick attributes.

Now in Level 3, we take a major step forward:

✅ We separate JavaScript from HTML
✅ We use addEventListener() to handle events the modern way
✅ We introduce conditional logic using if statements
✅ We write cleaner, more reusable and secure code


Why Separate JavaScript from HTML?

At first, writing everything in one file may seem easier. But as your project grows, mixing behavior (JavaScript) with structure (HTML) becomes messy and hard to maintain.

By separating code:

  • ✅ HTML focuses on structure
  • ✅ JavaScript handles behavior
  • ✅ Each part is easier to read, debug, and reuse

📌 Reusable code also means we need to write it safely, checking that elements actually exist on the page before using them.


Project Folder Structure

We’ll use two files:

pgsqlCopyEditshopping-list/
├── index.html
└── script.js

The HTML File – Structure Only

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Shopping List - Level 3</title>
</head>
<body>
<h1>My Shopping List</h1>

<input type="text" id="itemInput" placeholder="Add item..." />
<button id="addItemBtn">Add</button>
<ul id="shoppingList"></ul>

<!-- Link to external JavaScript -->
<script src="script.js"></script>
</body>
</html>

✅ No more onclick in the button. All behavior is now handled inside script.js.


The JavaScript File – Behavior Only

const itemInput = document.getElementById('itemInput');
const addItemBtn = document.getElementById('addItemBtn');
const shoppingList = document.getElementById('shoppingList');

// Check if all elements exist before adding behavior
if (itemInput && addItemBtn && shoppingList) {
addItemBtn.addEventListener('click', function () {
const itemText = itemInput.value.trim();

// Conditional logic: only proceed if input is not empty
if (itemText !== '') {
const li = document.createElement('li');
li.textContent = itemText;

// Add click event to remove the item
li.addEventListener('click', function () {
shoppingList.removeChild(li);
});

shoppingList.appendChild(li);
itemInput.value = '';
} else {
alert('Please enter an item.');
}
});
}

Explaining the Code – Step by Step

getElementById()

This function selects an HTML element by its id. We use it to interact with specific parts of the page.


addEventListener()

This is the modern way to assign actions to events like clicks or keyboard input.

Benefits:

  • HTML stays clean
  • You can assign multiple listeners
  • More flexibility and scalability

if (itemText !== '')

This is a conditional statement. It checks whether the user entered some text.

If true, it runs the code inside { ... }.
If false, it shows an error message.

Think of it like a traffic light:

  • If green → go
  • If red → stop

createElement() and appendChild()

These methods allow us to:

  • Dynamically create new elements
  • Add them to the page
  • Attach behavior (like click events) as we go

Verifying Elements Exist

If you reuse the same script.js in different pages, some elements might not be there. That’s why we check for their presence:

if (itemInput && addItemBtn && shoppingList) {
// Only run this code if everything exists
}

This prevents JavaScript errors like Cannot read properties of null.


Advantages of This Approach

BenefitDescription
✅ Clean separationEach file has one job: structure or behavior
✅ ReusabilityOne script file can be used on multiple pages
✅ Easier maintenanceYou know exactly where to fix things
✅ Safe conditionsCode won’t run if required elements aren’t present

Summary: What We Learned

ConceptPurpose
getElementById()Select page elements by ID
addEventListener()React to user actions (clicks, input, etc.)
if (condition)Decide whether or not to run a block of code
createElement()Create HTML elements on the fly
appendChild()Add an element to the page
removeChild()Remove an element from the page

What’s Next?

In Level 4, we’ll explore:

  • How to edit existing list items
  • Apply dynamic CSS classes
  • Save the list in your browser using localStorage

Ready to keep going?
Leave a comment or jump to the next step in your learning journey!

Post Views: 590

Condividi:

  • Condividi su Facebook (Si apre in una nuova finestra) Facebook
  • Condividi su X (Si apre in una nuova finestra) X
Javascript Coding

Navigazione articoli

Previous post
Next post

Francesco

My name is Francesco Boschi, originally from Italy and currently based in the United States. For over twenty years, I’ve worked as a manager and consultant across diverse sectors — from education and cultural institutions to the food industry — developing skills in operational management, strategic consulting, and complex problem-solving. In recent years, I’ve combined this experience with a strong passion for software development, creating custom tools designed to simplify workflows and meet real business needs.

Relocating to the U.S. marks the beginning of a new chapter: a personal and professional decision driven by the desire to be close to my son and to embrace new challenges in a different environment. Today, my goal is to turn my experience into meaningful solutions, blending strategic vision with technical expertise to help people and organizations work more effectively.

I enjoy moving between different worlds, adapting tools and approaches to people and contexts. I bring leadership, flexibility, attention to detail, analytical thinking, and a strong problem-solving mindset — along with a deep curiosity to learn and grow. Above all, I believe in sharing: I’m always eager to offer my experience to support the growth of others.

Related Posts

Coding

Coding – Step 10.6 — Pythin from zero – Final Project Polishing: Numbering, Formatting, and Preparing for CSV

Posted on 23 Agosto 202523 Agosto 2025

We finish our To-Do App by improving the output (numbered tasks and clear formatting) and setting up a simple structure for future CSV persistence.

Condividi:

  • Condividi su Facebook (Si apre in una nuova finestra) Facebook
  • Condividi su X (Si apre in una nuova finestra) X
Read More
Go

Coding – Step 12 – Go from Zero to “WoW”

Posted on 5 Settembre 202527 Settembre 2025

A fast and pragmatic expense tracker built in Go, designed for everyday use. Log your spending, filter by category, and save locally — no cloud, no clutter. A perfect example of how simplicity and speed can solve real-life problems.

Condividi:

  • Condividi su Facebook (Si apre in una nuova finestra) Facebook
  • Condividi su X (Si apre in una nuova finestra) X
Read More
Coding

Coding – Step 4 -Behind the Scenes of a Well-Built Customer Registration System

Posted on 8 Giugno 202526 Luglio 2025

A project that may seem simple, but is driven by purpose, philosophy, and technical precision. Introduction In today’s digital landscape, software interfaces are often judged at first glance. A registration form, for instance, might appear to be a trivial page—a set of fields and a submit button. But behind that…

Condividi:

  • Condividi su Facebook (Si apre in una nuova finestra) Facebook
  • Condividi su X (Si apre in una nuova finestra) X
Read More

Iscriviti alla nostra Newsletter

🤞 Let's keep in touch

We do not send spam! Read our Privacy policy for more information.

Controlla la tua casella di posta o la cartella spam per confermare la tua iscrizione

Cerca nel sito

©2026 This is my space, where experience meets the will to start over. | WordPress Theme by SuperbThemes