Button Logic

Hello there, I’m hoping someone can help me. I’ve added some buttons in the style of a sub menu at the top of my page. The page is long so these buttons link to anchors at sections on the page. I’m trying to figure out how I am able to code for having the text change colour on hover (mouse in) then return to its original colour when the cursor moves away (mouse out). When the button is clicked for it to stay the hover colour. Where I’m getting stuck is when I click the button and then move the cursor away from the button. The ‘mouse out’ function is executed returning the ‘clicked’ button back to the original colour! I assume I need to use some ‘logic’ code like an ‘IF’ statement. Unfortunately this goes beyond my current knowledge and I’m unable to find anything that refers to my immediate problem online. Please can someone help!

For the hover itself, you don’t need code at all. You can design it on the UI editor.


(and on EditorX, on the right-side bar)

So you can get rid of the onMouseIn and onMouseOut, and do something like:

const selectedStyle = {
    backroundColor: 'green',
    color: 'white'
};//set the style to be like in your hover state
const regularStyle = {
    backroundColor: 'blue',
    color: 'yellow'
};//use the same keys as in the selectedStyle
const styleKeys = Object.keys(selectedStyle);

$w.onReady(() => {
    const buttons = [$w('#button1'), $w('#button2'), $w('#button3')];
    buttons.forEach(btn => {
        btn.onClick(({ target }) => {
            buttons.forEach(e => {
                styleKeys.forEach(k => {
                    e.style[k] = e.id === target.id ? selectedStyle[k] : regularStyle[k];
                })
            })
        })
    })
})

Thanks very much. I’ll give it a go! I was using the ’onclick’ command to change the text colour in combination with the hover in the editor, however the hover part only seemed to work once for some reason.

Hi JD, thanks for your help yesterday as you can see from the attached I gave it a try but I still can’t seem to get it to take! There is a slight error on one of the parentheses where it tells me it was expecting a comma. I’m sure it’s something I’m doing wrong. Just for clarity here is a website that I’m trying to emulate the button funtionality of - www.crestron .com/products/featured-solutions/intelligent-video

As you can see there is a blue sub-menu that takes the viewer to the different anchor points.