Date & Time Display

Inserting a timestamp using traditional and modern JavaScript methods.

W3Schools Approach

Traditional Method

Date/Time Example (See original)

<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript</h1>

<button type="button" 
  onclick="document.getElementById('demo').innerHTML = Date()">
  Click me to display Date and Time.
</button>

<p id="demo"></p>

</body>
</html>

Try It

Analysis

✓ Pros

  • Very simple - all code in one place
  • Quick to write for small examples
  • Easy to see what happens when button is clicked

✗ Cons

  • Inline onclick mixes HTML and JavaScript (poor separation)
  • innerHTML can be a security risk (XSS vulnerability)
  • Date() returns awkward format (not user-friendly)
  • Hard to maintain in larger projects

Modern Approach

Current Best Practices

Date/Time Example

<!DOCTYPE html>
<html lang="en">
<body>
<h1>My First JavaScript</h1>

<button type="button" id="dateBtn">
  Click me to display Date and Time.
</button>

<p id="demo"></p>

<script>
  const btn = document.getElementById('dateBtn');
  const output = document.getElementById('demo');
  
  btn.addEventListener('click', () => {
    output.textContent = new Date().toLocaleString();
  });
</script>
</body>
</html>

Try It

Analysis

✓ Pros

  • Separates HTML and JavaScript (better organization)
  • Uses textContent (safer than innerHTML)
  • toLocaleString() formats date/time nicely
  • const and arrow functions = modern ES6+ syntax
  • addEventListener allows multiple handlers if needed

✗ Cons

  • Slightly more code to write
  • Requires understanding of event listeners
  • Arrow functions may be new concept for beginners

🎯 Key Takeaways

  • Separation of Concerns: Modern code separates HTML structure from JavaScript behavior
  • Security Matters: Use textContent for plain text; innerHTML can create XSS vulnerabilities
  • User Experience: toLocaleString() provides properly formatted, locale-aware dates
  • Maintainability: Event listeners scale better as projects grow
  • Both Work: W3Schools examples demonstrate concepts, but modern syntax is industry-standard