Utilizing SignalR to dynamically update a span's color based on real-time data source. The connection is established successfully, but encountering difficulties with updating the css classes on the span.
The issue arises when attempting to update multiple classes on a single element, as the class names are simply appended rather than replaced. Below is the markup:
<span id="activity-@UnitId" class="badge sl-badge-normal connection-false">
<i id="asxConnected-@UnitId" class="fa fa-rss"></i>
<span id="activityMessage-@UnitId">
@Model.ActivityMessage
</span>
</span>
Within the outer span, the classes sl-badge-normal
and connection-false
require modification.
sl-badge-normal
can be one of the following values:
- sl-badge-ok
- sl-badge-warning
- sl-badge-error
- sl-badge-normal
While connection-false
can only toggle between that and connection-true
.
Note that separate jQuery updates must be performed for these two distinct message types :) The jQuery code for the connection part is as follows:
messageHub.client.notifyAlive = function (aliveMessage, unitId) {
if (aliveMessage) {
$('#activity-' + unitId).addClass("connection-true");
} else {
$('#activity-' + unitId).addClass("connection-false");
}
};
And for the badge section, the jQuery code looks like this:
messageHub.client.notifyActivityStatus = function(statusColor, statusText, unitId) {
$('#activity-' + unitId).addClass("badge " + statusColor);
$('#activityMessage-' + unitId).text(statusText);
};
The problem lies in the fact that the span will transition from this initial state:
<span id="activity-@UnitId" class="badge sl-badge-normal connection-false">
To this unwanted state:
<span id="activity-@UnitId" class="badge sl-badge-normal connection-false sl-badge-error connection-true">
If anyone could provide a solution or suggest an alternative approach, it would be greatly appreciated. Is it necessary to restate the entire class string each time there's an update, or is there a way to simply swap out individual class names?