Code Block Element (codeblock)
codeblock element represents lines of program code. Line breaks, spaces, and indentation inside the element are preserved, and the content is typically rendered in a monospaced font.
The codeblock element serves these primary purposes:
-
Representing long portions of code or multiple lines of syntax with preserved formatting
-
Displaying preformatted text content that requires exact spacing
-
Supporting programming documentation within DITA topics
Key characteristics of the codeblock element:
-
Preserves all line endings and spaces inside the element
-
Content is typically rendered in a monospaced font
-
Can contain text data and various inline elements for semantic markup
-
Can be used within the
figelement to provide extra information in thedescelement
Content within the codeblock element generally follows these output formatting rules:
-
Renders in monospaced font (such as Courier or similar)
-
Appears with visual distinction such as background shading or borders
-
Display attributes can control scaling (
scale), framing (frame), page expanse (expanse), and syntax highlighting (outputclass)
Use codeblock for:
-
Long code samples and examples
-
Command-line instructions that require exact formatting
-
Configuration file contents
-
Any preformatted text where spacing and line breaks are significant
codeblock alternatives:-
For short, inline code samples, use
codeph -
For parameter names, for example, in an API, use
parmname
The codeblock element added to a task topic for showing JavaScript code with syntax highlighting added to a task element in the Heretto CCMS Content Editor:
The DITA source of the codeblock element with the surrounding context of a task:
<task id="task-6888">
<title>Adding Event Listeners to DOM Elements</title>
<shortdesc>Attach event listeners to HTML elements when building interactive web applications that respond to user actions like clicks, form submissions, or keyboard input.</shortdesc>
<prolog>
<author translate="no" type="creator">Heretto User <user@heretto.com></author>
<metadata>
<keywords/>
</metadata>
</prolog>
<taskbody>
<steps>
<step>
<cmd>Select the DOM element you want to attach an event listener to:</cmd>
<stepxmp>
<codeblock outputclass="lang-javascript">const button = document.getElementById('submitButton');
const form = document.querySelector('.contact-form');
const inputs = document.querySelectorAll('input[type="text"]');</codeblock>
</stepxmp>
</step>
<step>
<cmd>Add the event listener with your callback function:</cmd>
<stepxmp>
<codeblock outputclass="lang-javascript">button.addEventListener('click', function(event) {
event.preventDefault();
console.log('Button clicked!');
// Validate form data
if (validateForm()) {
submitForm();
}
});</codeblock>
</stepxmp>
</step>
</steps>
<result>
<p>The event listener is now attached and will execute when the specified event occurs.</p>
</result>
</taskbody>
</task>