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
<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.