Set a hype buttons state to display normal/hover/pressed?


(Paul ) #1

I have two buttons that are part of a form selector, option A option B etc… I need to be able to tell the buttons which state to display when pressed. The buttons set a variable with javascript :smile

setPackageOption(1)

Could I tell them when pressed to stay in the pressed state?

thanks in advance for any suggestions :smile:


#2

You could set the className onclick to a pre-set class of pressed / not-pressed.

You can’t really set the selector (:hover or :active or :visited ) via javascript as this is not really a rule but a state that can be applied to any element. What you should do is just create rules for different states and then change the className according to which state you want to display.

Look at element.classList.contains and element.classList.toggle for the javascript to manipulate selectors.

a simple approach:

if (element.classList.contains("option1")) {
    element.classList.remove("option1")
    element.classList.add("option2")
} else {
    element.classList.remove("option2")
    element.classList.add("option1")
}

you can change the check to whatever you want i.e your variable
and in your head you will have the styles

<style>
    .option1 {
	background-color: red !important;
    }
    .option2 {
	background-color: green !important;
    }
</style>

(Paul ) #3

Thanks, this looks great and have got the background colours working fine by the classes already set on the elements. I presume I need to remove the hard coded element classes now and set them by script so when the button is pressed the class name changes.

Sorry for my lack of javascript! how do I do that?

Thanks :slight_smile:


(Mark Hunte) #4

off the back of @Dbear’s method,

You can use the css,

	<style>

.option {background-color: red !important;}
.option.active, .option:hover { background-color: green !important; }

</style>

And then give the element the classname option. and run the from a Hype function:

element.classList.toggle('active');

or from within the forms element .

<input id="id1" type="number" min="100" max="300">
<button class="option" onclick="myFunction(event)">Use function in innerHTML and css</button>

<p id="demo"></p>

<script>
function myFunction(e) {
   
  e.target.classList.toggle('active');
   //--other stuff
}
</script>	

buttonStatus.hype.zip (23.5 KB)