Monday 6 July 2015

Changing background opacity of DOM Element dynamically with JQuery

jquery
Background opacity can be hard coded, but what about if you need to change the opacity dynamically!. JQuery makes your page more dynamic and interactive. In this section of code you can see how you can change the background opacity of a H1 element dynamically by changing the value in a combo list. Combo list consists of numbers from 0 to 100. 0 means fully transparent and 100 means fully opaque. Whenever you change the value opacity change. Try this code.

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {

   /* select list is dynamically created within a div with classname divOption, to fill it up with 0 to 100 using loop */
   var s="<select id='pct'>";
   for(i=0;i<=100;i++)
     s+="<option value=" + i + ">" + i + "</option>";
   s+="</select>";
   $("div.divOption").html(s);
   $("#pct").val("100"); // Set the current value to 100 that means fully opaque

   /* Initially when loading opacity is set to 1 i.e. fully opaque */
   $("h1").css({"color":"00FF00","fontSize":"36px","background-color":"rgba(0,0,255,1)"});

   $("#pct").change(function() {
 /* Follow the calculation in the change event,
since our combo value is 0 to 100, we divide it by 100 to get the fractional value */
     $("h1").css({"background-color":"rgba(0,0,255," + $(this).val()*1.0/100 + ")"});
   });
});   
</script>
<title>
</title>
</head>
<body>
<div class="divOption"></div>
<h1>Hello Subhroneel</h1>
</ br>
</body>
</html>


     

Hello Subhroneel

</ br>

No comments: