Free Videos about Mastering Views

Quick Tip: Allowing JavaScript in Blocks

Play Video
Movie link (right-click to download)
Problem with this video? Contact me

There are those few times when you want or need JavaScript to be allowed within blocks or nodes. The trick is simply to create a new Input Filter which does not use the HTML Filter.

Designate the filter for use by specific roles, and you're ready to rock and roll!

You just want to make sure only trusted users can use this input format. Most of the time, only the Admin user will be able to use it.

NOTE: the default Full HTML filter does allow you to post JavaScript. Creating your own additional filter with a unique name is simply be nice way to clearly identify what that filter does.

Hi Matt.

I just wanted to say thanks for this video and for showing me how to get javascript to work with Drupal. I'm developing a Drupal site and could not find out how to get done what you so nicely explained here.

Being relatively new to Drupal, it can be both frustrating and great to try and figure out how to do things. On the one hand I sometimes go a bit nuts trying to find out how to do something. I think this is largely a result of not being able to hit upon the right combination of keywords when searching. On the other hand if you keep at it you can usual find an answer to a problem. Occasionally you can even find a good explanation of the solution - which is what I found here. So at least for this situation I have gone from frustration to exhilaration.

I will be back to look at more of your videos!

While this technique is great for inserting small snippets of JavaScript, for more complicated scripts I do it differently. I place the JavaScript in a .js file and then include it using the drupal_add_js() function. In order to do this, I use the Input Filter that allows PHP code.

Granted this has the same security risks as allowing JavaScript. Indeed, one can really break a site by putting in PHP code that dies ungracefully. But it allows me to have complicated JavaScript code, which I can maintain in a separate file.

For example. if I have script in the sites/all/themes/mytheme/js folder called validate.js, I do this in the block:

<?php
drupal_add_js
(path_to_theme() .'/js/validate.js');
?>

Hope this is useful.