Submitted by manonamac on Wed, 06/01/2011 - 11:50
I recently found myself needing to add a little jQuery to a views output element. While I could have gone through the process of adding "scripts[] = whatever.js" to my theme's .info file, it would have loaded the jQuery on every page, which was unnecessary. I also could have added it to my front page .tpl template, but that would have required more steps going into Coda (which I love), opening the tpl file and editing it, saving it, and quite frankly not as much fun. For my needs, adding it to the View that was rendering the content was a lot faster since I already had the View open. But where to add the jQuery, and would it even work?
Views give you two extra regions for your view, a header and a footer. In there, you can add any code you want via the php filter input type. All I wanted to do was add a little jQuery to a close button, to allow the user to hide lengthy content on the sidebar if they wanted. So in my Views header I added the following:
<script>
(function ($) {
$(document).ready(function() {
$(".closebtn").click(function(){
$(".sidebar-testimonial").fadeToggle();
});
});
})(jQuery);
</script>
Presto magico! I now have a close button that hides my element via Views.