Adding Javascript to a Button

Hi there. I am experimenting with a page I am trying to build in Blocs and I have a button at the top within a navigation bar. I am experimenting with adding javascript to the button, and I cannot get it to work to save my life. In Blocs, I added an ID of “login-button” to the button and then included a js file at the end of the body. The javascript is exceedingly simple:

document.getElementById(“login-button”).addEventListener(“click”, () => loginClick());

function loginClick () {

// Change color of login button
document.getElementById("login-button").style.background = getRandomColor();

}

function getRandomColor () {

var colorNum = Math.floor(Math.random()*16777215).toString(16);
var color = "#" + colorNum;
return color;

}

When I deploy the whole package to firebase (where I am hosting the site) nothing happens. I know the js itself is written correctly because I have tested it in a basic html page locally. What do I need to be doing differently?

As a follow up, I have notice by examining the html in a text editor that the ID I assigned to the button in the Blocs UI was not implemented in the html. Thus, setting a ‘click’ listener using getElementById was not working. So I changed the javascript to listen on nav-toggle which is how the button is ID’d in the html but it still did not work.

Any thoughts on this matter would be appreciated!

Hello @zeeple, you have some errors in your code,

So there is fixed:

Add a button, and give It the ID you refer:

Then or in the code or as I do after the button add a HTML bric, and insert this code:

<script>
document.getElementById("login-button").addEventListener("click", loginClick(), false);

function loginClick () {

// Change color of login button
document.getElementById("login-button").style.background = getRandomColor();
}

function getRandomColor () {
var colorNum = Math.floor(Math.random()*16777215).toString(16);
var color = "#" + colorNum;
return color;
}
</script>

And there you go:

Hope it helps you…