Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

190
Views
why document.addEventListener() is not working in javascript

i am trying to execute the document.addEventListener() but it is not working why ?

<html>
<head>
    <title>javascript</title>
    <link rel="stylesheet" href="C:\Users\SUDARSHAN\Desktop\html_UI\eventstyle.css">
</head>

<body>
    <p id="p1">Welcome</p>
</body>
<script>
  
function f1() {
    document.getElementById("p1").style.fontSize="50px";
}

document.addEventListener("load",f1);
console.log("hello");

</script>
</html>
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You must append a load listener to window instead of document.

window.addEventListener("load",f1);

That being said, you cannot have a script element as a child of the html element, it must be in the head or body (which are the only allowed children of html). Always make sure your HTML is valid at all times; invalid HTML puts you in unspecified territory and tends to make things unpredictable (even if things seem to work).

about 4 years ago · Juan Pablo Isaza Report

0

Flaws in above code.

  1. Always make sure the html tag documented correctly. For ref https://www.w3schools.com/tags/tag_doctype.asp
  2. load event depends on window. In above code, you added the listener for document.
about 4 years ago · Juan Pablo Isaza Report

0

You can try following:

document.addEventListener('DOMContentLoaded', f1);

There are two events which are related to loading and unloading of the Document

  1. DOMContentLoaded
  2. readystatechange

Refer this page for windows events https://developer.mozilla.org/en-US/docs/Web/API/Document#load_unload_events

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!