Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

HTML Topics

HTML Attributes

Posted in HTML Tutorial
Updated on Nov 19, 2024
By Mari Selvan
👁️ 134 - Views
⏳ 4 mins
💬 1 Comment
HTML Attributes

Photo Credit to CodeToFun

🙋 Introduction

HTML attributes provide additional information about HTML elements. They are always included in the opening tag and come in name/value pairs.

In this reference guide, we'll explore commonly used HTML attributes to enhance your understanding and usage of HTML elements.

📑 Table of Contents

Some of the commonly used HTML attributes includes:

MethodsExplanation
acceptSpecifies the types of files that a file input can accept, restricting the selection to specific file formats.
accept-charsetSpecifies the character encodings that the server can accept when a form is submitted, ensuring proper handling of form data.
accesskeyDefines a keyboard shortcut for quick navigation to an element, enhancing accessibility and user experience.
actionSpecifies the URL where the form data should be sent upon submission.
alignUsed to horizontally align content within an element, but is now recommended to be replaced with CSS for styling (Deprecated).
altProvides alternative text for images, essential for accessibility and displaying text if the image fails to load.
asRefers to the practice of embedding HTML-like structures as values within HTML attributes, allowing for more dynamic and flexible content representation.
asyncUsed to indicate that a script should be executed asynchronously, allowing it to be loaded in the background without blocking the rendering of the page.
autocompleteEnables or disables browser autocomplete suggestions for form input fields, providing control over user data entry.
autofocusUsed to automatically focus on a specified form element when a page loads, enhancing user experience by directing attention to the relevant input field.
autoplayEnables audio or video elements to start playing automatically when a web page loads.
bgcolorUsed to set the background color of an element.
borderUsed to specify the border width of a table or table cell, defining the visual thickness of the border lines.
charsetSpecifies the character encoding for the document, ensuring proper interpretation of text, symbols, and special characters.
checkedUsed to set the default state of a checkbox or radio input, making it pre-selected or checked when the page loads.
citeUsed to provide a URL or reference to the source of a creative work, such as an article or quote, contributing to proper attribution and source acknowledgment in web content.
classUsed to assign one or more class names to an HTML element, enabling the application of styles and scripting to multiple elements with the same class.
colorDefines the text color of an element, enhancing visual styling on web pages.
colsSpecifies the number of columns in a textarea, influencing its visible width.
colspanDefines the number of columns a table cell should span, allowing for the creation of merged or combined cells in a table.
contentUsed to provide meta-information, such as character encoding or viewport settings, essential for proper rendering and functionality of a web page.
contenteditableAllows the user to edit the content directly within the designated element, transforming it into an editable area.
controlsUsed with the <audio> and <video> elements to display default media player controls for easy user interaction.
coordsUsed in image maps to define the coordinates of clickable areas, facilitating the creation of interactive and responsive web images.
dataProvide a way to store custom data private to the page or application, accessible via JavaScript and CSS.
data-*Provides a way to store custom data private to the page or application, facilitating more efficient and flexible JavaScript interactions.
datetimeProvides a standardized way to encode dates and times, enhancing accessibility and machine-readability on the web.
defaultSets a default value for an input element and is used when no other value is specified.
deferUsed to defer the execution of a script until after the HTML document has been fully parsed, enhancing webpage loading performance.
dirDefines the text direction of an element, indicating whether the text should be displayed from left to right or right to left.
dirnameUsed in input elements of type "file" to specify the direction in which the file names should be submitted.
disabledUsed to indicate that an element should be disabled and unresponsive to user interactions, such as clicks or keyboard input.
downloadAllows a user to download a linked resource, such as a file or image, directly through the browser.
draggableEnables the drag-and-drop functionality, allowing elements to be dragged and dropped within a web page.
enctypeSpecifies the encoding type used when submitting form data, with "multipart/form-data" commonly used for file uploads.
enterkeyhintUsed to suggest the action that will be triggered when the "Enter" key is pressed, providing a hint for user agents on the expected form submission or interaction behavior.
forUsed in label elements to associate the label with a specific form element, enhancing accessibility and user experience.
formSpecifies the form to which an input element belongs, facilitating seamless integration of form controls within a webpage.
formactionSpecifies the URL where the form data should be submitted, overriding the form's action attribute for the specific button it's associated with.
headersUsed in a table to associate data cells with header cells, enhancing accessibility and aiding assistive technologies in understanding the table structure.
heightSpecifies the height of an element, allowing control over its vertical dimension in web page layout.
hiddenUsed to hide an element from the user interface, making it invisible while still present in the HTML structure.
highUsed with the <meter> element to define the upper bound of the range represented by the meter.
hrefUsed to define the hyperlink reference, specifying the destination URL or the location of the linked resource.
hreflangSpecifies the language and regional targeting of a linked resource, aiding search engines in delivering the most relevant content to users based on their language preferences.
http-equivUsed to provide information to the browser about the document's HTTP header, allowing control over various aspects like page refresh and character encoding.
idProvides a unique identifier for an element, enabling targeted styling and scripting.
inertUsed to designate an element as inert, making it non-interactive and preventing user interaction within the specified element and its descendants.
inputmodeSpecifies the keyboard's input mode for an input field, aiding in optimal user experience on different devices.
ismapUsed to turn an image into a clickable image map, where different regions of the image can be linked to different URLs or actions.
kindUsed to specify the type of track in a media element, such as subtitles or captions for a video.
labelUsed to associate a label with a form element, enhancing accessibility and user experience.
langSpecifies the language of the document, aiding in proper rendering and accessibility for users with different language preferences.
listSpecifies the ID of a <datalist> element, providing a predefined set of options for an <input> element with autocomplete functionality.
loopUsed to specify the number of times a video should play, providing a simple way to control loop behavior in video elements.
lowSpecifies the lowest value in a range, typically used with the <meter> element to define the lower bound of a gauge or meter.
maxUsed to set the maximum value that a user can enter in an input element, defining an upper limit for numeric or date inputs.
maxlengthSets the maximum number of characters allowed in an input field, providing a client-side constraint for form data.
mediaSpecifies the conditions under which a linked stylesheet or external script should be applied, providing a means to control the rendering based on characteristics like device type, screen size, or media features.
methodSpecifies the HTTP method used when submitting a form, defining how data should be sent to the server.
minSpecify the minimum value allowed in an input element, enforcing user input constraints.
multipleAllows users to select multiple options from a list, providing enhanced flexibility in form selection.
mutedUsed to indicate that the audio content should be initially silenced when the page loads.
nameUsed to identify and reference form elements, enabling data collection and processing on the server side.
novalidateUsed to disable browser's native form validation, allowing custom JavaScript validation to be implemented without interference.
onabortExecuted when an image fails to load or is aborted.
onafterprintTriggers a JavaScript function after the document is printed or sent to a print preview.
onbeforeprintExecutes a script before the associated document is sent to the printer.
onbeforeunloadAllows executing a script before a user navigates away from a page, providing opportunities for confirmation or data-saving operations.
onblurExecutes JavaScript code when an element loses focus, allowing for actions to be triggered when a user moves away from that specific element.
oncanplayExecutes a script when a media element can start playing.
oncanplaythroughExecutes a script when a media element can be played through to the end without buffering.
onchangeTriggers a specified JavaScript function when the content of an input field or select dropdown is changed by the user.
onclickDefine JavaScript code that will be executed when an element is clicked, enabling interactive and dynamic web page behavior.
oncontextmenuSpecify a JavaScript code to run when the context menu (usually triggered by a right-click) is about to be displayed for an element.
oncopyTriggered when the user copies content from an element.
oncuechangeExecutes a script when the cue changes in a <track> element within an <audio> or <video> element.
oncutExecutes a script when the content of an element is cut.
ondblclickExecute when an element is double-clicked, adding interactivity to web elements.
ondragExecutes JavaScript code when an element is being dragged.
ondragendExecutes a script when a drag-and-drop operation is completed.
ondragenterTriggers a specified function when a dragged element enters a valid drop target.
ondragleaveExecutes a specified JavaScript code when an element is being dragged out of a valid drop target.
ondragoverSpecifies the action to be taken when an element is being dragged over, defining the behavior during the drag-and-drop operation.
ondragstartTriggers when a user starts dragging an element, enabling custom actions during the drag-and-drop process.
ondropSpecifies a JavaScript function to execute when an element is being dragged and dropped onto it.
ondurationchangeTriggered when the duration of an audio or video element changes.
onemptiedExecutes when a media element's playback is reset or aborted.
onendedExecutes a script when an audio or video element has finished playing.
onerrorExecuted when an error occurs while loading an external resource, such as an image.
onfocusExecutes JavaScript code when an element gains focus, such as when a user clicks on or tabs to the element.
onhashchangeTriggers a function when there's a change in the URL fragment identifier (hash) in the browser.
oninputExecutes JavaScript code when the user interacts with and changes the value of an input element in real-time.
oninvalidSpecify a JavaScript function that will be executed when a form element's value is invalid.
onkeydownExecutes a specified JavaScript function when a key is pressed down within an HTML element.
onkeypressExecutes a specified JavaScript function when a key is pressed within an input field or any element that can receive keyboard input.
onkeyupExecutes JavaScript code when a user releases a key after pressing it on a keyboard, commonly used for dynamic and real-time input validation or manipulation.
onloadExecute a script or trigger an action when a web page has finished loading in the browser.
onloadeddataExecutes a JavaScript function when data for the current frame is loaded in a media element.
onloadedmetadataTriggers a JavaScript function when the metadata of an audio or video element has been loaded.
onloadstartExecutes a specified JavaScript code when the loading of an element or media begins.
onmousedownDefines JavaScript code to be executed when a mouse button is pressed down over an element.
onmousemoveUsed to execute JavaScript code when the mouse pointer moves over an element, enabling dynamic interactivity in web pages.
onmouseoutUsed to define JavaScript code that should be executed when the mouse pointer moves out of an HTML element.
onmouseoverTriggers a JavaScript function when the mouse cursor moves over the specified element.
onmouseupDefines JavaScript code to be executed when the mouse button is released over an element.
onmousewheelExecutes JavaScript code when the mouse wheel is rotated over an element.
onofflineExecutes a specified JavaScript function when a browser's online/offline status changes.
ononlineExecutes a specified JavaScript code when the browser goes online.
onpagehideExecutes a specified JavaScript code when the browser goes online.
onpageshowExecutes a script when a page is being loaded, either for the first time or due to a navigation forward.
onpasteExecutes a script when the user pastes content into an input field or a contenteditable element.
onpauseExecutes JavaScript code when audio or video playback is paused.
onplayTriggered when a media element starts playing.
onplayingExecutes a specified JavaScript function when media playback begins.
onpopstateExecutes JavaScript code when the user navigates through the browser history.
onprogressExecutes a specified JavaScript function as a resource is being loaded, providing a way to monitor and respond to the progress of data transfer.
onratechangeTriggered when the playback rate of a media element changes.
onresetExecuted when a form is reset, providing a way to define custom behavior when the user resets form input fields.
onresizeExecutes JavaScript code when the browser window or an element is resized.
onscrollTriggers a script or action when an element is scrolled, providing dynamic control over user interactions.
onsearchExecutes JavaScript code when the user initiates a search within a search input element.
onseekedTriggers a JavaScript function when seeking (moving to a different position) in an audio or video element has completed.
onseekingExecutes when the seeking operation begins on an audio or video element.
onselectExecutes JavaScript code when a user selects text within an input or textarea element.
onstalledExecutes JavaScript code when media playback is delayed or interrupted.
onstorageTriggers JavaScript code when a web storage area (localStorage or sessionStorage) in the browser is modified.
onsubmitUsed to specify a JavaScript function that will be executed when a form is submitted.
onsuspendExecutes JavaScript code when media loading is suspended.
ontimeupdateTriggers a function when the playback position of a media element, such as an audio or video player, is updated during playback.
ontoggleExecutes JavaScript code when a <details> element's disclosure box is toggled open or closed.
onunloadExecutes a script when a user navigates away from a page, providing an opportunity to perform actions before the page unloads.
onvolumechangeExecutes JavaScript code when the volume of an audio or video element changes.
onwaitingExecutes JavaScript code when media playback is paused due to buffering.
onwheelExecutes JavaScript code when the mouse wheel is rotated over an element.
openSpecifies whether the link should open in a new tab or window when clicked.
optimumUsed in the <meter> element to suggest the optimal numeric value, providing a hint to browsers for gauging the user's preferences.
patternUsed to specify a regular expression that an <input> or <textarea> element's value must match to be considered valid, providing client-side form validation.
placeholderProvides a brief hint or example text within an input field, guiding users on the expected input format.
popoverEnables the creation of interactive, small overlays that appear when triggered by user actions, enhancing user experience and providing contextual information.
popovertargetSpecifies the target element for a popover, providing a reference point for positioning and displaying additional content.
popovertargetactionDefines the action to be triggered when interacting with the target of a popover in a user interface.
posterUsed in the <video> element to specify an image that represents the video, serving as a poster frame before the video is played.
preloadUsed to hint to the browser that a specific resource should be fetched and cached, enhancing page performance by preloading essential assets.
readonlyUsed to make an input field or textarea non-editable, preventing user modification while still allowing them to view the content.
relSpecifies the relationship between the current document and linked resources, influencing how browsers interpret and display linked content.
requiredEnsures that a form element must be filled out before submitting the form, adding client-side validation for user input.
reversedUsed within ordered lists (<ol>) to reverse the numbering of list items, creating a descending order from the highest to the lowest number.
rowsSpecifies the visible height of a text area, defining the number of visible lines in a textarea element.
rowspanUsed to define the number of rows a table cell should span, allowing the efficient creation of row spans in tables.
sandboxUsed in iframes to create a secure, isolated environment, restricting certain behaviors to enhance web page security.
scopeUsed in table elements to define the set of data cells that the header (th) element relates to, aiding accessibility and providing context in complex tables.
selectedUsed to preselect an option in a dropdown list or select box.
shapeUsed in conjunction with the coords attribute to define the shape and coordinates of a clickable area within an image map.
sizeSpecifies the visible width of an input element, particularly useful for defining the width of text input fields in forms.
sizesSpecifies the sizes of responsive images based on the conditions of different media queries.
spanUsed to apply styles or scripting to a specific portion of text within a larger block, providing flexibility in formatting.
spellcheckUsed to enable or disable the browser's spell-checking functionality for a specific element.
srcSpecifies the source URL or file path for external resources, such as images or scripts, to be embedded within an HTML document.
srcdocSpecifies inline HTML content to be displayed in an <iframe>, providing a concise way to embed content directly within the tag.
srclangSpecifies the language of the track data for the HTML <track> element.
srcsetAllows responsive web design by specifying multiple image sources with varying resolutions, helping the browser choose the most appropriate one for the user's device.
startUsed with ordered lists (<ol>) to specify the starting value for the list items.
stepSpecifies the interval between legal numbers in an input field, providing a defined increment for numeric input values.
styleUsed to add inline CSS styles to an HTML element, allowing for the customization of appearance directly within the HTML document.
tabindexDefines the order in which an element receives focus when navigating through a webpage using the Tab key.
targetSpecifies the browsing context for a hyperlink, determining where the linked content will be displayed.
titleProvides supplementary information about an element, typically displayed as a tooltip when the user hovers over the element.
translateUsed to specify whether an element's content should be translated when a webpage is localized, offering control over language translation behavior.
typeSpecifies the type of content, input, or functionality associated with an element, influencing its behavior and display.
usemapUsed to associate an image with a client-side image map, allowing different regions of the image to be clickable and linked to various URLs or actions.
valueUsed to set the initial or default value of an input element, providing a predefined value that users can interact with or submit in a form.
widthSpecifies the width of an element, defining its horizontal dimension either in pixels or as a percentage of its containing element.
wrapSpecifies whether the text in a <textarea> should be wrapped or not when submitted in a form.

🚀 Usage Tips

Explore the following tips to make the most out of HTML attributes:

  1. Semantic HTML:

    Use attributes to add semantic meaning to your HTML, making it more accessible and understandable.

  2. Global Attribute:

    Some attributes can be applied to any HTML element (global attributes). Familiarize yourself with these to enhance flexibility.

  3. Accessibility:

    When using attributes like alt or aria-*, consider accessibility to ensure a positive user experience.

  4. Responsive Design:

    Attributes like width and height can be crucial for responsive web design. Utilize them effectively.

📝 Example

Let's look at a practical example of using HTML attributes in an image element:

example.js
Copied
Copy To Clipboard
<!-- Example: Using HTML attributes in an image element -->
<img src="example.jpg" alt="An example image" width="300" height="200" style="border: 1px solid #ddd;">

This example showcases the use of src, alt, width, height, and style attributes in an <img> element to display an image with specific dimensions and a border.

🎉 Conclusion

This reference guide provides an overview of essential HTML attributes. By understanding and utilizing these attributes, you can enhance the structure, styling, and functionality of your HTML documents. Experiment with different attributes and explore their impact on the presentation and behavior of HTML elements.

👨‍💻 Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mari Selvan
Mari Selvan
11 months ago

If you have any doubts regarding this article (HTML Attributes), please comment here. I will help you immediately.

We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy