ggv
ggv

Reputation: 109

Changing style in javascript on onclick

I want to make a few simple buttons that toggle color each time they are pressed. With a button press also some unique string needs to be passed to the server. Therefore on every button press I run two functions. My problem is that when I run this script, button changes color to red only for the period after the alert message Msg1 is displayed. When I answer OK to the Msg2, the color of the button reverts back to green. What am I doing wrong here?

<style>
.button { background-color: green; }
.buttonOn { background-color: red; }
</style>

<button id="r1" class="button" onclick="mF1(id)">Relay 1</button>

<script>

function mF1(btn) {
var property = document.getElementById(btn);
alert('Msg1: This is ' + property.className);
if (property.className == 'button')     
    { property.className = 'buttonOn' }
else 
    { property.className = 'button';  }
alert('Msg2: This is ' + property.className);
mF2(btn);            
}

function mF2(id) { window.location.href='?HVAC-' + id; }

</script>

Upvotes: 0

Views: 31

Answers (1)

Quentin
Quentin

Reputation: 943157

You are using JavaScript to change the DOM.

Then you are setting location.href to a new value.

This causes a new page to load.

The new page does not have the modifications you made to the DOM.


You would need to write code that examines the query string when the page loads and sets the appropriate classes.

Upvotes: 2

Related Questions