Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • HTML Tutorial
  • HTML Exercises
  • HTML Tags
  • HTML Attributes
  • Global Attributes
  • Event Attributes
  • HTML Interview Questions
  • HTML DOM
  • DOM Audio/Video
  • HTML 5
  • HTML Examples
  • Color Picker
  • A to Z Guide
  • HTML Formatter
Open In App
Next Article:
HTML DOM onmousedown Event
Next article icon

How to use DOM and Events ?

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

DOM (Document Object Model), a programming interface that is used to connect web pages to scripts by representing the structure of a document such as HTML documents. It defines the way a document is to be accessed and manipulated and also defines the logical structure of documents.

The way DOM represents a document is with a logic tree ( DOM Tree ).

To provide a dynamic interface to a webpage, we use events in JavaScript . These events are attached to elements in the DOM ( Document Object Model ). By default, events use bubbling propagation i.e from children to parent. Events can be bound either as inline or in the external script (JavaScript file).

Using DOM and Events: Suppose we want to make changes in the document or stylesheet on a certain event. The event can be the loading of a web page, selection of any specific element or a form is submitted, etc.

Some common event attributes are as follows.

  • Window Event Attributes: These events are triggered for the window object.
    • onload: It fires after the page is finished loading.
    • onresize: It fires when the browser window is resized.
  • Mouse Events: These are the most common events with basic interaction of user through the mouse.
    • onclick: It fires when a mouse click is triggered on an element.
    • onmouseover: It fires when a mouse pointer moves over an element.
    • ondblclick: It fires on a mouse double click on the element
  • KeyBoard Events:
    • onkeydown: It fires when the user is pressing a specific key
    • onkeyup: It fires when a user releases a specific key

Example 1: In this example, we are attaching an event listener to our container. When the click event happens, the text color inside the container changes from white to black.

HTML
<!DOCTYPE html>
<html>
<head>
<title>DOM and Events</title>
  <style>
    .container {
            height: 150px;
            width: 300px;
            background-color: green;
            text-align: center;
            color: white;
            font-size: 30px;
            margin: auto;
            font-weight: bolder;
            font-family: -apple-system, BlinkMacSystemFont,
                        'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell,
                        'Open Sans', 'Helvetica Neue', sans-serif;
        }
  </style>
</head>
<body>  
    <div class="container">GeeksforGeeks</div>
    <script>
        let container = document.querySelector('.container');
        container.addEventListener('click', function(e) {
            container.style.color = "black";
        });
    </script>  
</body>
</html>

Output:


use DOM and Events

Example 2: In this example, a keyboard event is taking place, we are attaching an event Listener on our input element. When the user is pressing an 'Enter' key, a message prompt is shown to the user saying "You Pressed an Enter".

HTML
<!DOCTYPE html>
<html>

<head>
    <title>DOM and Events</title>
    <style>
        * {
            font-family: -apple-system, BlinkMacSystemFont,
              'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 
              'Open Sans', 'Helvetica Neue', sans-serif;
        }
    </style>
</head>

<body>
    <h3>
        Message will be displayed when 
        you press a Enter key
    </h3>

    <input type="text" class="inputArea">
    <p></p>

    <script>
        let input = document.querySelector(".inputArea");
        let p = document.querySelector("p");
      
        input.addEventListener('keydown', function(e) {
            if (e.keyCode == 13) {
                p.textContent = "You pressed an Enter";
            }
        })
    </script>
</body>

</html>

Output:



Next Article
HTML DOM onmousedown Event

S

siddharth01
Improve
Article Tags :
  • HTML
  • HTML-DOM
  • JavaScript-Questions

Similar Reads

    HTML DOM onmouseup Event
    The HTML DOM onmouseup event occurs on the release of a pressed button on a mouse over an element. Related events for left-click: onmousedownonmouseuponclick Related events for right-click: onmousedownonmouseuponcontextmenu Supported Tags: It supports All HTML elements, EXCEPT: <base><bdo
    1 min read
    HTML | DOM Storage Event
    The Storage Event in HTML DOM is used to make change in the storage area in the context of another document. When there is modification in the storage area of the window, a storage event is sent to that window. Syntax: window.addEventListener("storage", script) Example: html <!DOCTYPE html>
    1 min read
    HTML DOM onmousedown Event
    The HTML DOM onmousedown event occurs when a mouse button is pressed over an element. It's useful for implementing interactive features that respond to mouse clicks or taps on web elements. Syntax: In HTML<element onmousedown="myScript"> In JavaScriptobject.onmousedown = function(){myScript};
    1 min read
    HTML DOM onmousedown Event
    The HTML DOM onmousedown event occurs when a mouse button is pressed over an element. It's useful for implementing interactive features that respond to mouse clicks or taps on web elements. Syntax: In HTML<element onmousedown="myScript"> In JavaScriptobject.onmousedown = function(){myScript};
    1 min read
    HTML DOM onmousedown Event
    The HTML DOM onmousedown event occurs when a mouse button is pressed over an element. It's useful for implementing interactive features that respond to mouse clicks or taps on web elements. Syntax: In HTML<element onmousedown="myScript"> In JavaScriptobject.onmousedown = function(){myScript};
    1 min read
    HTML DOM onmouseover event
    The DOM onmouseover event in HTML occurs when the mouse pointer is moved onto an element or its children. Supported Tags: It supports All HTML elements, EXCEPT: <base><bdo><br><head><html><iframe> <meta><param><script><style><title> S
    1 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • DSA Tutorial
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences