Creating a Button in Javascript

I want to create a button using Javascript in Lectora, set the position/size/text/style properties of the button, then tell that button to do something when clicked.


Edit: I'm attempting to dynamically populate the screen with buttons in multiple courses based on the number of variables. I have a script now that grabs all the variables, now I want to create a button for each variable.

Discussion (5)

It would help to understand why you want to do this?

Unless you are experienced with Javascript, my suggestion would be to just make a hidden button in Lectora & add all of the actions to it then "show" the button when the time is right.

Thanks for the reply, Susan. I've edited the topic to include more detail.

Allthough i mostly work in Lectora Online and not in Lectora Desktop its almost the same routine. Except for some selectors that differ in Online.


First of all you can create either HTML-elements or Canvas-elements in Lectora.

Thats basically pure HTML, CSS and Javascript.


These lines of code create a button. Use a loop if you want to create a lot of them.


const newButton = getDisplayDocument().createElement('button');
newButton.textContent = 'Click me!';
newButton.id = "bttn01";
newButton.className = "myBttn";
getDisplayDocument().body.appendChild(newButton);


newButton.addEventListener('click', () => {
 console.log('New button clicked!');
});


Depending on what you exactly want to achieve, this can be improved.


PS. getDisplayDocument() is Lectora Online specific. In Lectora Desktop you can replace that by document

One other approach is 'cloning' an existing element and changing the properties of that element.

On a game i needed tiles and made this function to 'clone' existing elements to create a gameboard.


This code clones a bttn and duplicates it. I will mock up a sample showing both methods.


const node = getDisplayDocument().getElementsByClassName("customBttn")[0];
const clone = node.cloneNode(true);


let wndPage = getDisplayDocument().querySelector("#wndPage");
wndPage.appendChild(clone);



Basically the added Lectora Online pkg should work in Desktop too. It shows how to create and clone a button.


I use GSAP for moving, animating and getting attributes from HTML elements. Without it it is a lot more cumbersome especially because you have to take a lot into account. Absolute or relative position. Left vs x. Responsive sites. Canvas DOM versus HTML DOM and more like that. GSAP all does that automatically and thus makes it a breeze to get positions, size and more...and set it. Out of scope for now to show all GSAP makes possible... but the sample thus lacks proper positioning...


Mmm...how you add an attachment here ?