Auto select in stock Variant

Hello everyone,

I would like to implement a function that automatically selects a variant in stock. To make it more understandable I will show an example:

When user enters the product page these variants are selected automatically:

Color: Blue

Size: M

When the user selects another color the size remains being M. So it could happen that the user selects a variant where the M size is out of stock, for example:

Color: Red

Size: M

So this is my problem. Anyone knows how to automatically change the variant of size to another one in stock?

Thank You.

My page