HTML id Attribute

HTMLWeb DevelopmentFront End Technology

The HTML id attribute is used to allocate a unique identifier to an element to single out that element for application of CSS and JavaScript on it. No two elements can have the same id in a single HTML page. Id’s start with an octothorpe (#).

NOTE − As of HTML5 id’s starting with a number are allowed to be specified.

Let’s see an example for id attribute −


 Live Demo

<!DOCTYPE html>
<title>MouseEvent clientX</title>
   * {
      padding: 2px;
   form {
      margin: 0 auto;
      text-align: center;
   #outer {
      margin: 0 auto;
      padding: 0;
      text-align: center;
      border:1px solid black;
      height: 105px;
      background-color: #28a745;
   input[type="button"] {
      border-radius: 10px;
   #upper {
      border-bottom: 1px solid black;
      height: 40px;
      margin: 0 0 15px 0;
      background-color: #DC3545;
   #lower {
      border-top: 1px solid black;
      height: 40px;
      margin: 15px 0 0 0;
      background-color: #DC3545;
<div id="outer">
<div id="upper"><h2>Danger</h2></div>
<div id="lower"><h2>Danger</h2></div>
<input type="button" id="start" value="Start" onclick="gameStart()">
<div id="divDisplay"></div>
   var divDisplay = document.getElementById('divDisplay');
   var gameDisplay = document.getElementById('outer');
   function playGame(event) {
      var x = event.clientX;
      var y = event.clientY;
      if(y > 95 &amp;&amp; y < 110){
         divDisplay.textContent = 'Keep Going!';
         if(x === 439){
            divDisplay.textContent = 'Congrats! You Did it!';
            gameDisplay.removeEventListener('mousemove', playGame);
      } else {
         divDisplay.textContent = 'You moved to DANGER area. You loose!';
         gameDisplay.removeEventListener('mousemove', playGame);
   function gameStart(){

This will produce the following output −

1) After clicking ‘Start’ button and cursor in green (safe) area −

2) After clicking ‘Start’ button and cursor at end of green (safe) area −

3) After clicking ‘Start’ button and cursor in red (danger) area −

Published on 19-Sep-2019 16:10:12