HTML Topics
- HTML Intro
- HTML Basic
- HTML Editors
- HTML CSS
- HTML Tags
- HTML Deprecated Tags
- HTML Events
- HTML Event Attributes
- HTML Global Attributes
- HTML Attributes
- abbr
- accept
- accept-charset
- accesskey
- action
- align
- alt
- archive
- as
- async
- autocapitalize
- autocomplete
- autofocus
- autoplay
- axis
- bgcolor
- border
- cellpadding
- cellspacing
- char
- charoff
- charset
- checked
- cite
- class
- classid
- codebase
- codetype
- color
- cols
- colspan
- compact
- content
- contenteditable
- controls
- coords
- crossorigin
- data
- data-*
- datetime
- declare
- default
- defer
- dir
- dirname
- disabled
- download
- draggable
- enctype
- enterkeyhint
- for
- form
- formaction
- formenctype
- formmethod
- formnovalidate
- formtarget
- frame
- frameborder
- frameset
- headers
- height
- hidden
- high
- href
- hreflang
- hspace
- http-equiv
- id
- inert
- inputmode
- ismap
- kind
- label
- lang
- list
- loop
- low
- max
- maxlength
- media
- method
- min
- multiple
- muted
- name
- novalidate
- onabort
- onafterprint
- onbeforeprint
- onbeforeunload
- onblur
- oncanplay
- oncanplaythrough
- onchange
- onclick
- oncontextmenu
- oncopy
- oncuechange
- oncut
- ondblclick
- ondrag
- ondragend
- ondragenter
- ondragleave
- ondragover
- ondragstart
- ondrop
- ondurationchange
- onemptied
- onended
- onerror
- onfocus
- onhashchange
- oninput
- oninvalid
- onkeydown
- onkeypress
- onkeyup
- onload
- onloadeddata
- onloadedmetadata
- onloadstart
- onmousedown
- onmousemove
- onmouseout
- onmouseover
- onmouseup
- onmousewheel
- onoffline
- ononline
- onpagehide
- onpageshow
- onpaste
- onpause
- onplay
- onplaying
- onpopstate
- onprogress
- onratechange
- onreset
- onresize
- onscroll
- onsearch
- onseeked
- onseeking
- onselect
- onstalled
- onstorage
- onsubmit
- onsuspend
- ontimeupdate
- ontoggle
- onunload
- onvolumechange
- onwaiting
- onwheel
- open
- optimum
- pattern
- placeholder
- popover
- popovertarget
- popovertargetaction
- poster
- preload
- readonly
- rel
- required
- reversed
- rows
- rowspan
- sandbox
- scope
- selected
- shape
- size
- sizes
- span
- spellcheck
- src
- srcdoc
- srclang
- srcset
- start
- step
- style
- tabindex
- target
- title
- translate
- type
- usemap
- value
- width
- wrap
- HTML Comments
- HTML Entity
- HTML Head
- HTML Form
- HTML IndexedDB
- HTML Drag & Drop
- HTML Geolocation
- HTML Canvas
- HTML Status Code
- HTML Language Code
- HTML Country Code
- HTML Charset
- MIME Types
HTML onerror Attribute
Photo Credit to CodeToFun
🙋 Introduction
The onerror
attribute is a powerful feature in HTML that allows developers to handle errors that may occur while loading an external resource, such as an image or a script.
This attribute is commonly used to provide fallback mechanisms or log errors when a resource fails to load.
🎯 Purpose of onerror
The primary purpose of the onerror
attribute is to specify a JavaScript function to be executed when an error occurs during the loading of an external resource.
This enables developers to take specific actions, such as displaying an alternative image or logging the error for further analysis.
💎 Values
The onerror
attribute accepts a JavaScript function as its value. This function will be triggered when an error occurs. Here's a simple example:
<img src="example.jpg" onerror="handleError()">
🧠 How it Works
In this example, if the image with the source "example.jpg" fails to load, the handleError JavaScript function will be executed.
📄 Example
Let's look at a more comprehensive example of how to use the onerror
attribute:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>onerror Attribute Example</title>
<script>
function handleImageError() {
console.log("Error loading image!");
document.getElementById("fallbackImage").src = "fallback.jpg";
}
</script>
</head>
<body>
<img src="example.jpg" onerror="handleImageError()" id="fallbackImage" alt="Fallback Image">
</body>
</html>
🧠 How it Works
In this example, if the image with the source "example.jpg" encounters an error, the handleImageError JavaScript function is called.
This function logs an error message and sets the source of an alternative image ("fallback.jpg") to provide a fallback.
🔄 Dynamic Values with JavaScript
You can dynamically set the onerror
attribute using JavaScript, allowing for more flexibility in handling errors based on different conditions or user interactions:
<script>
// Dynamically set onerror for an image
document.getElementById("dynamicImage").onerror = function() {
console.log("Dynamic image loading error!");
this.src = "dynamic-fallback.jpg";
};
</script>
🧠 How it Works
In this script, the onerror
attribute is dynamically set for an image with the id dynamicImage. If an error occurs while loading this image, a JavaScript function is executed to log an error message and set a dynamic fallback source.
🏆 Best Practices
- Use the
onerror
attribute to gracefully handle errors and provide fallbacks for critical resources like images or scripts. - Ensure that the JavaScript function assigned to onerror is well-defined and handles errors appropriately.
- Test your error-handling mechanisms across different browsers to ensure compatibility.
🎉 Conclusion
The onerror
attribute is a valuable tool for managing errors when loading external resources in HTML.
By leveraging this attribute, developers can enhance the robustness and reliability of web applications.
👨💻 Join our Community:
Author
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
If you have any doubts regarding this article (HTML onerror Attribute), please comment here. I will help you immediately.