Power of HTML CSS and jQuery collapsible CSS Table

Minggu, 02 Februari 2014

It’s generally recommended you ensure the vast majority of your web page content is immediately visible when someone accesses it – but there are exceptions where you would want to display only the summarized view to not clutter up the page and expand to the details as and when required by clicking on a button or an icon. Here is a very simple tutorial on HTML, CSS, and jQuery that shows how to create a collapsible table. The following code snippet has embedded CSS with the style tag and jQuery with the script tag. The HTML defines the DOM (Document Object Model) structure. The CSS is used to hide and unhide the relevant rows. The jQuery is used to add and remove CSS styles.


Try using this example on Firefox with Firbug turned on or on Goggle chrome with the dEV tools turned on with the "F12" function key. This will enable you to inspect the HTML elements and the styles.

<!DOCTYPE html>
<html>
<head>
<title></title>

<script src="http://code.jquery.com/jquery-1.8.3.js"></script>

</head>
<body>

<h1>demo for hiding and unhiding table rows </h1>

<button id="myappSummaryCollapse">
<span class="collapse">Collapse</span>
<span class="expand">Expand</span>
</button>

<table class="collapsible">
<tr class="collapsible"><td>collapsible row</td></tr>
<tr><td>not collapsible row</td></tr>
</table>


<script>

jQuery(#myappSummaryCollapse).click(function () {
var button = jQuery(this);
var tables = jQuery(table.collapsible);

if (button.hasClass(collapsed)) {
button.removeClass(collapsed);
for (var i = 0; i < tables.length; i++) {
jQuery(tables[i]).removeClass(collapsed);
}
} else {
button.addClass(collapsed);
for (var i = 0; i < tables.length; i++) {
jQuery(tables[i]).addClass(collapsed);
}
}
});

</script>



<style>

#myappSummaryCollapse .expand,
#myappSummaryCollapse.collapsed .collapse,
table.collapsed tr.collapsible {
display: none;
}

#myappSummaryCollapse.collapsed .expand {
display: inline;
}

</style>


</body>
</html>


Very often, simple examples like the one above can clarify things to go on and do more complex scenarios. In the CSS, #myappSummaryCollapse is the element id and ".expand" is the style class name. "display:none" is used to hide and "display:inline" is used to display. The jQuery is used to add and remove the CSS classes.


Similar results can be achieved using JavaScript directly as shown below.

document.getElementById("p2").style.color="blue";


or

<button onclick="document.getElementById(id1).style.color=red" type="button">
</button>



But, jQuery selectors are very powerful and let you achieve similar results with less code.

Related Posts by Categories

0 komentar:

Posting Komentar