Adding javascript to a new block with on_page_view

Permalink
I'm trying to add some javascript to the header with the block controller method:

public function on_page_view() {
        $this->addHeaderItem('<script type=\"text/javascript\" src=\"js/jquery.fitvids.js\"></script>');
   }


And then in my view, call the jquery library:

<script> 
  $(document).ready(function(){
    // Target your .container, .wrapper, .post, etc.
    $("#video-<?php echo intval($bID)?>").fitVids();
  });
</script>


I placed the file in my package
-js
--jquery.fitvids.js

However when I install my package and try to add my block, it hangs (i.e. won't finish adding the block) and then in my console I see a javascript error:

Uncaught TypeError: Object [object Object] has no method 'fitVids'


To me it looks like the FitVids library is not getting added to the header when I add the block to the page?

 
mhawke replied on at Permalink Reply
mhawke
Try looking at the 'View Source' of the page and finding the line that calls 'js/jquery.fitvids.js'. See what path C5 attached to it.
nicolechung replied on at Permalink Reply
Okay, this is what I am getting:

<script type=\"text/javascript\" src=\"js/jquery.fitvids.js\"></script>


It looks like it's including my backslashes...

Also how do I include my javascript? Do I just make a "js" folder in my package?
andrew replied on at Permalink Best Answer Reply
andrew
The backslashes aren't necessary in your function because you're using single quotes to start and end the string. Just remove the backslashes and it should be fine.
nicolechung replied on at Permalink Reply
Okay, that helps and I also figured out that I should put my javascript inside of my block folder (not my package folder)

I did it this way, if there's a better way...?

$bv = new BlockView();
      $bv->setBlockObject($this->getBlockObject());
      $blockURL = $bv->getBlockURL();
      $html = Loader::helper('html');
      $this->addHeaderItem($html->javascript("{$blockURL}/js/jquery.fitvids.js"));
mhawke replied on at Permalink Reply
mhawke
I would suggest you go to the marketplace and grab the add-on called 'Designer Content'.

http://www.concrete5.org/marketplace/addons/designer-content/...

With this free add-on (courtesy of jordanlev), you can create a block and then dig into the files it creates in your root/blocks folder to see how a 'standard' block is laid out.

It helped me immensely when I first started building with C5. I still use it at least once a week to create the starting point for a block which I then customize from there.