Appfarm Documentation
Getting startedDocumentationCommunityAppfarm Create
  • Overview
  • Getting Started
    • What is Appfarm?
    • Key concepts
    • Quickstart
      • Speed intro
      • Step-by-step guide
    • Appfarm Showroom
    • FAQ
  • Appcademy
    • Learning paths
    • Appfarm Fundamentals
      • Intro Course
        • 1. Intro to No-Code and Appfarm
        • 2. Navigation in Appfarm Create
        • 3. What is Apps?
        • 4. Intro to UI Editor
        • 5. Data Model
        • 6. App Data
        • 7. Actions
        • 8. Tips and Tricks
        • 9. Intro to practical walkthrough
        • 10. Create a details view of a Project
        • 11. Create a Custom List
        • 12. Swipe and Delete
        • 13. Functionality for simple Create of Data
        • 14. Upload and Download Photos
        • 15. Input Dialog with Validation and Save
        • 16. Dashboard
        • 17. Summary
        • Quiz
      • User Interface Fundamentals
        • Container - Sectioning, Styling and Repeating
        • Conditional Styles
        • Motions
        • Responsive Design
        • Step-by-step workflow
        • Featured UI Components
        • Quiz
      • App Data Fundamentals
        • Data Source Filtering
        • App Variables and Runtime Properties
        • URL Parameters
        • Quiz
      • Actions & Logic Fundamentals
        • Event Handlers
        • Featured Action Nodes
        • Context Parameters
        • Quiz
      • Services Fundamentals
        • Introduction to Services
        • Setting up a Service
        • Scheduling a Service
      • Integration Fundamentals
        • The web request action node
        • Fetch data from an endpoint
        • Map data to a data source
        • Modify the response
        • Nested data mapping
        • Path parameters
        • Authentication
        • Send data to an endpoint
        • Quiz
      • User handling and permissions
        • Users and roles
        • Permissions
        • Creating users
        • Extending the User object class
        • Updating and deleting users
        • Unauthenticated access
        • Quiz
    • Appfarm Professional
      • User Interfaces
        • Featured UI Components
        • Concepts and Use Cases
      • Data Structures & Data Handling
        • Data Features
        • Search & Filters
        • Featured Action Nodes
        • GraphQL
      • Logic & Flow
        • Logical Concepts
        • Date and Time Handling
        • Featured Action Nodes
        • Exception Handling
      • Login & Configuration
        • Login and Authentication
        • Settings, Configuration and Languages
      • Security & Operations
        • Security and Permissions
        • Deployment
        • Schedules and Logs
        • Debugging and App Health
      • Performance & Optimization
        • Optimizing Performance
        • Enhancing Functionality
    • Appfarm Sales Representative
    • Appfarm Developer Forum
      • Session 1: Data Modeling in Appfarm Create
      • Session 2: App Data in Appfarm Create
      • Session 3: Services in Appfarm Create
      • Session 4: Optimizing Performance
    • Background
      • Databases
        • Data modeling 101
        • Database normalization
  • Library
    • UI components
      • Advanced bar chart
      • Advanced bubble chart
      • Advanced combined chart
      • Advanced gantt chart
      • Advanced heatmap chart
      • Advanced line/area chart
      • Advanced pie chart
      • Advanced scatter plot chart
      • Advanced solid gauge chart
      • Animated component
      • Avatar
      • Avatar group
      • Basic bar chart
      • Basic gauge chart
      • Basic line chart
      • Basic pie chart
      • Bottom navigation
      • Button
      • Checkbox
      • Chip group
      • Circular progress
      • Coded component
        • Coded component examples
      • Container
      • Date & time picker
      • Drawable canvas
      • Floating action button
      • Icon
      • Icon button
      • Iframe
      • Image
      • Linear progress
      • List
      • Map
      • Menu list
      • Multi select
      • PDF reader
      • Popover
      • Radio buttons
      • Rich text editor
      • Rich text
      • Select
      • Slider
      • Speed dial
      • Switch
      • Table
      • Tabs
      • Text
      • Text edit
      • View container
      • Visibility group
    • Action nodes
      • Aggregate data
      • Advanced search
      • Auth operations
      • Block
      • Catch exception
      • Copy to clipboard
      • Create file archive
      • Create file object
      • Create object
      • Create user account
      • Delete objects
      • Delete user account
      • Duplicate objects
      • End execution
      • Exit block
      • Exit loop
      • Export data
      • Foreach
      • Generate document
      • If
      • Import data
      • Invalidate cache
      • Log in
      • Log to console
      • Log out
      • Next iteration
      • Navigate
      • Open/close popover
      • Open confirm dialog
      • Open print dialog
      • Open snackbar
      • Open Unsplash dialog
      • Open URL
      • Persist objects
      • Push notifications
      • Read objects
      • Request permissions
      • Run code
      • Run other action
      • Run service
      • Scan barcode/QR code
      • Send email
      • Send SMS
      • Set client language
      • Set data source attributes
      • Set selection
      • Set theme
      • Set user account image
      • Show install app prompt
      • Sleep
      • Sort objects
      • Throw exception
      • Toggle drawer
      • Update object
      • Update secret
      • Update user account
      • Web request
      • While
  • Reference
    • Appfarm Create
      • Appfarm Commander
      • Blue dots
      • Copy & Paste
      • Farmer's Market
      • Find references
      • Find usage
      • Keyboard shortcuts
      • Undo/Redo
      • User preferences
    • Platform concepts
      • Conditions
      • Data bindings
      • Date and time
      • Event handlers
      • Filters
      • Functions
      • Markdown
      • Objects
      • Operators
      • Value processor
    • Dashboard
    • Apps
      • UI
        • Views
          • Dialog
          • Drawer
        • Layout designer
        • Component properties
        • Shareable UI components
      • Data
        • App variables
        • Data sources
        • Calendar data sources
      • Actions
      • App settings
      • App size
      • App health
    • Services
      • Service Endpoints
      • Service settings
      • Service health
      • API explorer
    • Data model
      • Object classes
      • Object class properties
      • Enumerated types
      • GraphQL
        • Queries
        • Mutations
      • Data Extract API
      • Time series data
    • Operations
      • Deploy
      • Schedules
      • Logs
    • Resources
      • Themes
      • Files
      • Fonts
      • Internationalization
    • Configuration
      • Environments
      • Login
        • Custom auth providers
    • Security
      • Users
      • Service accounts
      • Roles
      • Secrets
      • Permissions
        • Conditional Permissions
    • Appfarm Client
      • Developer tools for Apps
      • Developer tools for Services
      • Warnings and errors
  • How to
    • Data modeling
      • Many-to-many relationships
      • Use naming conventions
      • Offline data handling
      • Data silos and White labelling
    • User interface
      • Manage a many-to-many relationship with a Chip group
      • Configure drag and drop
      • Build a drag-and-drop calendar
      • Design a responsive layout
      • Work with flexbox
      • Use Mapbox as a map layer
      • Understand charts
    • Logic and flow
      • Event Log Design
      • Configure advanced search
    • Themes and styling
      • Change the active theme
      • Add custom email templates
    • Enhance your app
      • Add deep links
      • Add keyboard shortcuts
      • Add link previews for social media
      • Apply SEO best practices
      • Change the active language
      • Generate a PDF from a Container
    • Integrations
      • Integrate with external systems
      • Integrate with OpenAI
      • Integrate with Google Analytics (GA4)
      • Configure a custom email account
      • Integrate with a payment provider
      • Integrate with Signicat
      • Integrate directly with an external database
      • Retrieve a Bearer token from Google Cloud
      • Fetch data from BigQuery
      • Retrieve access token from Microsoft Entra ID
    • Workflow automation
      • Update an OAuth 2.0 access token from a service
    • Authentication and access control
      • Add users and assign roles
      • Configure unauthenticated access
      • Implement third-party authentication
    • Security, testing and deployment
      • Add a custom domain
      • Install an app on a device
      • Get ready for Production
      • Optimize performance
      • Security checklist
      • Test and debug
    • Example apps
      • Create an Instagram clone
        • The end result
        • Designing the feed
        • Create new post
        • Add a like-button
        • Add comment-functionality
  • Solution administration
    • Subscription and billing
    • Dedicated tier benefits
    • Guide to GDPR
      • Key principles
      • How Appfarm protects personal data
      • How you can protect your clients’ data
      • Glossary
    • Appfarm and the EU AI Act
  • Policies
    • Appfarm Policies
    • Data Processors
    • Privacy Policy
Powered by GitBook
On this page
  • Getting an element from the DOM
  • Setting the value of a paragraph
  • Listening to events
  • Getting data from appfarm
  • Calling actions
  • CSS
  • Importing scripts and stylesheets

Was this helpful?

Export as PDF
  1. Library
  2. UI components
  3. Coded component

Coded component examples

This page contains example code for some general use cases for the Coded component

PreviousCoded componentNextContainer

Last updated 9 days ago

Was this helpful?

Getting an element from the DOM

The DOM is a representation of a webpage that allows for programs to change it´s state, structure and content. The DOM also contains all of your HTML elements like `<div>` and `<p>`. You can read more about the DOM .

To achieve this, use the `querySelector` method documented .

HTML Content
<!--- HTML defined in the HTML Content property -->

<p id="text-content">My Text</p>
<button>Sign Up!</button>

We can retrieve these elements from `Script` property.

Script
// If you have defined a custom namespace on the Coded Component, use that instead
const textParagraph = appfarm.element.querySelector("#text-content") // Get an element by ID
const myButton = appfarm.element.querySelector("button") // Will get the first button in the DOM

// Do things with your paragraph and button...
// ...

Setting the value of a paragraph

If you have an `HTMLElement` that you wish to update the value of, you can do so like this. This will work for many other `HTMLElements` as well. You can read more about `innerHTML` .

HTML Content
<!--- HTML defined in the HTML Content property -->

<p id="text-content">My Text</p>
Script
const textParagraph = appfarm.element.querySelector("#text-content")
textParagraph.innerHTML = "New Value" // The paragraph will now show the "New Value" instead of "My Text"

Listening to events

HTML Content
<!--- HTML defined in the HTML Content property -->

<button>Sign Up!</button>
Script
const signUpButton = appfarm.element.querySelector("button")

// Add an eventListener to listen for "click" - events

// The first argument is the event to listen to, and the second is a callback that will be executed when the "click" event happens
signUpButton.addEventListener("click", (event) => {
    alert("Thank you for signing up!")
})

Now, every time the user clicks the button, an alert dialog will appear.

Getting data from appfarm

In this example, we have defined an App Variable of type string in our model. This App Variable has been added as a `Read Only Value` on our Coded Component, with the name `userInput`. In the UI outside the Coded Component, this is bound to a TextEdit. To make the text from the TextEdit appear in our Coded Component, we can get the data from the App Variable.

HTML Content
<!--- HTML defined in the HTML Content property -->

<p id="text-content"></p>
Script
// In the script property

const output = appfarm.element.querySelector("#text-content")

// Get the data from userInput. This will only run once. 
const userInput = appfarm.data.userInput.get()
output.innerHTML = userInput

// Listen to changes to userInput and update the value of the output on every change
appfarm.data.userInput.on("change", (value) => {
    output.innerHTML = value
})

Calling actions

You can also call actions from the Coded Component. There is also support for Action Params. In this example, we will call an action that opens a snackbar. The action takes one required Action Param, which is the text to show. The action has been added to the Coded Component and the Action Param `snackbarText` is databound as a `Code Function Param`. In the Coded Component, there is an input element and a button.

HTML Content
<!--- HTML defined in the HTML Content property -->

<input type="text" placeholder="Input a value"></input>
<button>Open Snackbar</button>
Script
const inputElement = appfarm.element.querySelector("input")
const button = appfarm.element.querySelector("button")

// Disable the button if there is no value in the inputElement
inputElement.addEventListener("input", (event) => {
    const hasValue = !!event.data
    
    if (hasValue) {
        button.disabled = false
    } else {
        button.disabled = true
    }
})

button.addEventListener("click", (event) => {
    const userValue = inputElement.value

    // Actions in Appfarm are promises. You don't *have* to await them, but doing so is recommended for handling errors.
    appfarm.actions.openSnackbar({ snackbarText: userValue })
        .then(() => console.info("Called action successfully"))
        .catch(error => alert(`Failed to call action. Error: ${error}`))
})

CSS

Inlining styles in HTML can be tedious. You can instead add stylesheets to your Coded Component from the Resources property. In this example we will defined our own stylesheet, but you can also import external stylesheets by choosing the "Stylesheet URL" - option.

Stylesheet
/* Styles for all p elements */
p {
  color: red;
}

/* Styles for all elements with the class "button-primary" */
.button-primary {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

The CSS for p - elements will also affect all other p - elements in your Appfarm app and is therefore not recommended. Consider using classes instead

HTML Content
<p>My Text</p>
<button class="button-primary"">Button 1</button>
<button class="button-primary"">Button 2</button>
<button class="button-primary"">Button 3</button>

Importing scripts and stylesheets

Animation might not work if you have "Reduce Motion" enabled on your computer

Styles
  .h1 {
     color: #333;
     margin-bottom: 20px;
 }

 .button {
     padding: 10px 20px;
     font-size: 1.1em;
     cursor: pointer;
     background-color: #007bff;
     color: white;
     border: none;
     border-radius: 5px;
     transition: background-color 0.3s ease;
 }

 .button:hover {
     background-color: #0056b3;
 }

 .message {
     margin-top: 30px;
     font-size: 1.5em;
     color: #28a745;
     padding: 15px;
     border: 1px solid #28a745;
     border-radius: 8px;
     background-color: #e6ffed;
 }
HTML Content
<h1 class="h1 animate__animated animate__bounce">Packages Demo</h1>

<button id="triggerAnimation" class="button button:hover">Click Me for Animation!</button>

<p class="message" id="animatedMessage" style="display: none;">
    Voila! Animate.css is working!
</p>
Script
appfarm.element.querySelector('#triggerAnimation').addEventListener('click', () => {
    const messageElement = appfarm.element.querySelector('#animatedMessage');


    // Use a class provided by Animate.css
    // Remove previous animation classes to allow re-triggering
    messageElement.classList.remove('animate__fadeOut', 'animate__animated', 'animate__bounceIn');
    messageElement.style.display = 'block';

    // Add new animation classes
    messageElement.classList.add('animate__animated', 'animate__bounceIn');


    console.log({ messageElement })
    setTimeout(() => {
        messageElement.classList.remove('animate__bounceIn');
        messageElement.classList.add('animate__fadeOut');
        messageElement.addEventListener('animationend', () => {
            messageElement.style.display = 'none';
        }, { once: true });
    }, 2000); // Wait 2 seconds before fading out
});

Listening to events is necessary if you want to act on user input. In this example, we will listen to a button, but this pattern can be used for more `HTMLElements`. You can read more about EventListeners .

You can read more about the input-element .

Scripts and stylesheets can be added to your resources as either `Script URL` or `Stylesheet URL`. This allows you to use external libraries to extend the functionality of the Coded Component. In this example we will add and to our Coded Component. In order to load external libraries in an Appfarm app, you also need to whiteliste the domain in the Environment settings for your solution. In this case, that would be `cdnjs.cloudflare.com` for `Script Sources` and `Style Sources`.

When using external libraries, these will be added to the Window object which you can read more about . To check that your packages have been added correctly, attempt to call `window.dayjs` in your browser console.

here
here
here
here
here
dayjs
animate.css
here
624KB
Screen Recording 2025-05-20 at 13.33.46.mov
Video showcasing the animations