In HTML, global attributes and event attributes are two types of attributes that can be used with almost every HTML elements.
Global Attributes
These attributes are common to all HTML elements. They can be used with many HTML tag.
Some common global attributes include:
- id: Specifies a unique identifier for an element.
- class: Specifies one or more class names for an element, allowing you to apply CSS styles to it.
- style: Allows you to specify inline CSS styles for an element.
- title: Provide additional information about the element when hover on that element.
- lang: Specifies the language of the content within the element.
- data-*: Allows you to store custom data attributes.
Here's an example of how global attributes can be used:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML <hr> Tag</title>
</head>
<style>
#myDiv{
max-width: 300px;
border:2px solid #04AA6D;
font-size: 18px;
font-weight: 700
}
.highlighted{
padding: 12px 25px;
text-align:center;
margin: 25px auto 0 auto;
border-radius: 5px;
}
</style>
<body>
<div id="myDiv" class="highlighted" style="color: #04AA6D;" title="This is a div element">This is a Content</div>
</body>
</html>
Output
Event Attributes
These attributes are used to define JavaScript actions or functions that should be executed when a particular event occurs on an element.
Some common event attributes include:
- onclick: Specifies a JavaScript code to be executed when the element is clicked.
- onmouseover: Specifies a JavaScript code to be executed when the mouse pointer moves over the element.
- onkeydown: Specifies a JavaScript code to be executed when a key is pressed down while the element has focus.
- onload: Specifies a JavaScript code to be executed when the element (such as an image or a document) is finished loading.
Here's an example of how event attributes can be used:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Attributes in HTML</title>
</head>
<body>
<button onclick="alert('Button clicked!')">Click me</button>
</body>
</html>
Output