Home > HTML, MVC, Spark View Engine > Tip: Using Spark Conditionals to Toggle CSS and JavaScript

Tip: Using Spark Conditionals to Toggle CSS and JavaScript

January 3, 2012

The conditional attribute is a fantastic shortcut to toggle CSS, input boxes, and other elements on a page–and is something I don’t see used in very many examples. One of my favorites is applying classes to an element based on a output model property, such as a permission boolean.

Here’s an example.

In a recent project, a dashboard screen had several charts that toggled on and off based on the user’s preference. Rather than rebuild the screen each time, each class simply toggled an ‘enabled’ class based on a Model.{Property}.

<div class="charts">
    <div id="enteredbycount" class="loading enabled?{Model.ShowEnteredBy}"
		style="inlineChart">
	</div>
    <div id="schoolcount" class="loading enabled?{Model.ShowSchoolCount}"
		style="inlineChart">
	</div>
</div>

The Spark Conditional only renders the text preceding the conditional ?{} if the condition is true. In this example, if our Model.ShowSchoolCount returns false, enabled never renders and our chart (due to some styling), remains hidden and never posts back to the server to get the chart data (saving an unnecessary AJAX call).

By toggling a class, you can trigger a certain set of styles, events using JavaScript, or most anything else you can dream up.

%d bloggers like this: