BlecKent
BlecKent

Reputation: 33

Using javascript, how can I change opacity with ON and OFF?

I want that users can change opacity by clicking on ON(opacity 100%) or OFF(opacity 0%) and not 1 or 0. Is that possible? The code:

<!DOCTYPE html>
<html>
<body>

<p id="p1">Change this phrase's opacity</p>   

<select onchange="myFunction(this);" size="2">
<option>0  <!--I want this OFF not 0-->
<option selected="selected">1 <!--I want this ON not 1-->
</select>

<script>
function myFunction(x) {
   var opacity = x.options[x.selectedIndex].text;
   var el = document.getElementById("p1");
   if (el.style.opacity !== undefined) {
      el.style.opacity = opacity;
    } else {
        alert("Your browser doesn't support this!");
    }
}
</script>

</body>
</html>

Upvotes: 0

Views: 153

Answers (1)

Nope
Nope

Reputation: 22339

If you can change the options to have values you can do the following:

function myFunction(x) {
  var opacity = x.options[x.selectedIndex].value;
  var el = document.getElementById("p1");
  if (el.style.opacity !== undefined) {
    el.style.opacity = opacity;
  } else {
    alert("Your browser doesn't support this!");
  }
}
<p id="p1">Change this phrase's opacity</p>

<select onchange="myFunction(this);" size="2">
  <option value="0">OFF</option>
  <option value="1" selected="selected">ON</option>
</select>

Upvotes: 2

Related Questions