How to generate width CSS from JavaScript / C#
Tags: c#,javascript,asp.net,html,css
Problem :
I have been trying to get my C# variables values communicate with my HTML code through JavaScript the last couple of days, and now I have this HTML code which I would like to change through the value from C# upon page load. Upon page load I would like to set the css width value of the SPAN through JavaScript from my c# variable value.
The progressBarPercentage SPAN is the one I would like the set the CSS Width, since that's how my jQuery Progress Bar would like the values. The width would be as a percentage, therefore on it's own this would work:
<span id="progressBarPercentage" style="width: 40%"></span>
But this is what I am trying to do:
HTML
<div id="progressBarArea" class="progress-bar orange stripes">
<asp:Label ID="progressBarText" runat="server" Visible="true" Text="49%" CssClass="progressBarText"></asp:Label>
<span id="progressBarPercentage" onload="setProgressBarPercentage()"></span>
<p class="align-center">Points Until Next Level: <asp:Label id="pointsUntilNextLevelLabel" runat="server" Text="0" CssClass="pointsUntilNextLevelLabel"></asp:Label></p>
</div>
C#
protected double percentageLevelComplete { get; set; }
JavaScript
<script type="text/javascript">
function setProgressBarPercentage(){
var element = document.getElementById("progressBarPercentage");
element.style.width = <%=percentageLevelComplete%> + "%";
}
</script>
Is what I am doing the right way to go? If so, what am I doing wrong since this is not working at the moment.
Solution :
You can use this code (without javasript):
<div id="progressBarArea" class="progress-bar orange stripes">
<asp:Label ID="progressBarText" runat="server" Visible="true" Text="49%" CssClass="progressBarText"></asp:Label>
<span id="progressBarPercentage" style="width:<%=percentageLevelComplete %>%"></span>
<p class="align-center">Points Until Next Level: <asp:Label id="pointsUntilNextLevelLabel" runat="server" Text="0" CssClass="pointsUntilNextLevelLabel"></asp:Label></p>
</div>