Reputation: 1810
Technology: Asp.Net 4.5 WebForms
I am using the following javascript function to color text in a code block. It actually works if I halt the code with an alert immediately after the function. But the regex rendering doesn't stick. How can I get the results to render after function is completed? Below is a small sample.
CSS
<style type="text/css">
.blue
{
color: blue;
}
.demo
{
background-color: gainsboro;
width: 300px;
height: 100px;
padding: 5px;
}
</style>
JavaScript
<script type="text/javascript">
function Prettyfy() {
var keys = ["Dim", "As", "String"]
for (var i = 0; i < keys.length; i++) {
var value = keys[i];
var str = document.getElementById("demo").innerHTML;
var regexExpression = "(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b";
var regex = new RegExp(regexExpression, "ig");
document.getElementById("demo").innerHTML = str.replace(regex, '<span class="blue">' + value + '</span>');
}
alert(document.getElementById("demo").innerHTML);
}
</script>
HTML
<body>
<form id="form1" runat="server"> <pre id="demo" class="demo">
<code>
dim motor as string
dim reducer as string
</code>
</pre>
<br />
<button onclick="Prettyfy()">Prettyfy Code</button>
</form>
</body>
Upvotes: 0
Views: 145
Reputation: 413709
The problem is very likely to be that your form is causing the page to be repainted by default. Add a "type" attribute to your <button>
:
<button type=button onclick="Prettyfy()">
(It's not clear why there's a form at all.)
Upvotes: 1