StartseiteWeblogs / robertDouglass's blog / Views + jQuery rocks my world
Views + jQuery rocks my world
Sometimes Drupal just makes me sit back and say "wow!" I had one of those moments yesterday when I set about tweaking the theming for the sessions page. I wanted to make it clear which language was going to be spoken in each session. My goal was to change the background color depending on whether the session is in English or German. I have access to the Drupal administration section, but I don't have direct server access. This makes it hard to write CSS for the page. Besides, CSS isn't equipped to look into a table cell, see its contents, and theme accordingly. jQuery is, however, and using Views you can add JavaScript directly to the page! So how'd I do it? Let's look at the HTML, first:
<td>
<a href="/tag/6%20-%20Community.61/">6 - Community</a>
<a href="/node/205">DVC - Introduction</a>
<a href="/user/43" title="Benutzerprofil anzeigen.">SirFiChi</a>
Deutsch
</td>
It's slightly simplified from the real code, but the main point is, it's a TD element that contains either the word 'Englisch' or 'Deutsch'. So the trick is to write some jQuery that selects TD's looks inside for either of those words, and sets the CSS styling of the element accordingly.
Here's the jQuery code:
<script>
// This is the jQuery syntax for doing something after
// the HTML is loaded,
// but before the page has rendered.
$(document).ready(function() {
// Get each TD in the grid view,
// and give it some padding.
$("table.views-view-grid td").css({padding: "0.5em"});
// use td:contains('Englisch') to find TD elements
// with the word Englisch, and give
// them a background color.
$("table.views-view-grid td:contains('Englisch')")
.css({background: "#FFFFCC"});
// Do the same for 'Deutsch',
// but with a different color.
$("table.views-view-grid td:contains('Deutsch')")
.css({background: "#CCFFFF"});
});
</script>
With the code in hand, I needed a place to put it. Here's where Views comes to the rescue. Each page View has a header and footer section that can be free text. I used the header to inject the jQuery code into the page. Note that I used the PHP Filter not because any PHP code is executing, but because it doesn't do any other filtering (like line breaks).

The result? A nice and color-coded sessions page!
- robertDouglass's blog
- Anmelden um Kommentare zu schreiben















