Hi Ivo,
I’ve done functionalities like this in the htmlsnippet, and you should set the eventlistener to the window
window.mx.addOnLoad(function() {
myFunction()
});
function myFunction(){
// do something here
}
Hope this helps
Here is a solution with modern-day technology called jQuery.
Ever since the html-snippet has the option ‘JavaScript with jQuery’, you have the option to listen to the ‘document loaded’-event. See this code bit that sets focus to an input element that has classname ‘focusonme’:
$( document ).ready(function() {
let narcissus=$('.focusonme')[0]; //Obviously: add class 'focusonme' to the desired input
if (typeof narcissus !='undefined'){
let myinput = narcissus.firstChild;
myinput.focus();
}});
Hello from 2025 :)
For me, just applying myinput.focus()
doesn't work - the element gets the focus for a split while, and then the focus moves to navigation elements from the layout.
So, I applied a different strategy - instead of setting focus on the desired element, I changed tabindex of layout elements to -1 (to make them unfocusable).
In my case, the culprit was the navigation menu. Unfortunately, you cannot set tabindex for navigation items in studio, so I had to use javascript (utilizing HTML Snippet):
Step 1
Open the layout and select the container where you hold the elements you want to ignore when setting focus:
Step 2
Add a class to that container, e.g. no-focus
Step 3
Add HTML snippet to the layout
window.mx.addOnLoad(function() {
clearTabIndex()
});
function clearTabIndex(){
const parentElement = document.querySelector('.no-focus');
if (parentElement) {
// Select all children within the parent
const focusableElements = parentElement.querySelectorAll(
'*'
);
// Set tabindex to -1 for each child
focusableElements.forEach((element) => {
element.setAttribute('tabindex', '-1');
});
}
}
and that's it - now the layout is not focusable, the focus will be automatically set to page elements based on their tab indexes, so you can just put the lowest tab index on the one you want to set the focus to (by default all are 0, so the first one is picked).
And you just do it once in the layout, no need for additional HTML snippets on pages.
And of course remember to copy the layout and edit it in your module rather than directly in the marketplace modules folder.