Topic: Injecting Javascript into view (Beginner Question)

Hello, I am relatively new to RoR and completely new to Javascript.  I am trying to take example javascript code from THEJIT graphing tool and inject it into my view.  Can't seem to find a tutorial anywhere on how to go from zero to deployment with it so I am hoping I can get some help here.

function barGraph()
{
    var json = {
        'label': ['label A', 'label B', 'label C', 'label D'],
        'values': [
            {
                'label': 'date A',
                'values': [20, 40, 15, 5]
            },
            {
                'label': 'date B',
                'values': [30, 10, 45, 10]
            },
            {
                'label': 'date E',
                'values': [38, 20, 35, 17]
            },
            {
                'label': 'date F',
                'values': [58, 10, 35, 32]
            },
            {
                'label': 'date D',
                'values': [55, 60, 34, 38]
            },
            {
                'label': 'date C',
                'values': [26, 40, 25, 40]
            }]

    };

    var barChart = new $jit.BarChart({
        //id of the visualization container
        injectInto: 'infovis',
        //whether to add animations
        animate: true,
        //horizontal or vertical barcharts
        orientation: 'vertical',
        //bars separation
        barsOffset: 20,
        //visualization offset
        Margin: {
            top:5,
            left: 5,
            right: 5,
            bottom:5
        },
        //labels offset position
        labelOffset: 5,
        //bars style
        type: useGradients? 'stacked:gradient' : 'stacked',
        //whether to show the aggregation of the values
        showAggregates:true,
        //whether to show the labels for the bars
        showLabels:true,
        //labels style
        Label: {
            type: labelType, //Native or HTML
            size: 13,
            family: 'Arial',
            color: 'white'
        },
        //add tooltips
        Tips: {
            enable: true,
            onShow: function(tip, elem) {
                tip.innerHTML = "<b>" + elem.name + "</b>: " + elem.value;
            }
        }
    });
    //load JSON data.
    barChart.loadJSON(json);
    return barChart;
}

Just trying to call this function (barGraph) from my view in order to display the graph.

Last edited by ChrisL1200 (2012-02-14 13:41:06)

Re: Injecting Javascript into view (Beginner Question)

First,  your function returns barChart,  what is in that variable?,  html that when rendered  displays a barChart?

Assuming that is the case you can just add this to your view:

<script type='text/javascript'>
$(window).bind("load", function() {
  # put your javascript here
  $('#mydiv).html(barGraph);
});
</script>
<div id='mydiv'>
</div>

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Injecting Javascript into view (Beginner Question)

Sorry small change


  $('#mydiv).html(barGraph());

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Injecting Javascript into view (Beginner Question)

I am not 100% sure what barChart is exactly but the code you gave me does not seem to output anything so i guess it might not be an HTML object?  I inserted your code and where u said Javascript here I pasted in what I had. Here is the barChart class from thejit, not sure if this helps.  I am just at the beginner stages of all this so I apologize for the lack of detail in my questions.

$jit.BarChart = new Class({
  st: null,
  colors: ["#416D9C", "#70A35E", "#EBB056", "#C74243", "#83548B", "#909291", "#557EAA"],
  selected: {},
  busy: false,
  
  initialize: function(opt) {
    this.controller = this.config = 
      $.merge(Options("Canvas", "Margin", "Label", "BarChart"), {
        Label: { type: 'Native' }
      }, opt);
    //set functions for showLabels and showAggregates
    var showLabels = this.config.showLabels,
        typeLabels = $.type(showLabels),
        showAggregates = this.config.showAggregates,
        typeAggregates = $.type(showAggregates);
    this.config.showLabels = typeLabels == 'function'? showLabels : $.lambda(showLabels);
    this.config.showAggregates = typeAggregates == 'function'? showAggregates : $.lambda(showAggregates);
    
    this.initializeViz();
  },
  
  initializeViz: function() {
    var config = this.config, that = this;
    var nodeType = config.type.split(":")[0],
        horz = config.orientation == 'horizontal',
        nodeLabels = {};
    
    .
    .
    .
});

Re: Injecting Javascript into view (Beginner Question)

Look at the example you posted:
notice the line:

        <ul id="id-list"></ul>

that is where the bar chart eventually ends up:

notice this line:

<script language="javascript" type="text/javascript" src="example2.js"></script>

go back to the demo site,  and click on the example2.js and you should have a page with all that javascript,  copy it all and put it in

public/javascripts/example2.js

If you look in example2.js,  you'll see 'id-list',  that is where the example2.js is told what element on your page to put the chart

Then notice this line the original example you posted:

<body onload="init();">

So when you load the example page,  it will call the init() function defined in example2.js,  and put the bar char in the <ul id='id-list'></ul>

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Injecting Javascript into view (Beginner Question)

actually a better way, the rails way

replace

<script language="javascript" type="text/javascript" src="example2.js"></script>

with

<%= javascript_include_tag 'example2' %>
or change it to

<script language="javascript" type="text/javascript" src="/javascripts/example2.js"></script>

or copy example2.js to your app's /public

and the original example I posted will work.

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Injecting Javascript into view (Beginner Question)

Trying to test exactly what you are asking; If I put my example2.js into my app/assets/javascripts folder (it is where all my javascripts usually go) and then in my view put in the line:

<script language="javascript" type="text/javascript" src="/javascripts/example2.js"></script>
<ul id='id-list'></ul>

Is this supposed to display the chart where I put ul id?  Do I need to edit the example2.js or do I leave it as is?  Thanks again for being very insightful, all of this is brand new!

Re: Injecting Javascript into view (Beginner Question)

I think what you should do is visit this page:

http://thejit.org/static/v20/Jit/Exampl … mple2.html

Then 'view source',  and copy that page,  railsify it where nessecary,  copy the referenced javascript,  and there is some css you'll need to copy as well

For example,  their example2.html has

<body onload='init();' >

That has to be in your view to call the example2.js init() function,  which sets everything up and makes the magic happen.

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Injecting Javascript into view (Beginner Question)

I have copied there HTML into my view, have the javascript, have the css files (all come in there download); however I still don't get what they get outside of the hardcoded text.  The CSS files are in app/assets/stylesheets, Javascripts files are in app/assets/javascripts. 
How should I set up the "src = .." to represent these libraries.  I have tried various ways and I still do not get a chart so I am trying to cover all potential problems. 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>BarChart - Bar Chart Example</title>

    <!-- CSS Files -->
    <link type="text/css" href="../css/base.css" rel="stylesheet" />
    <link type="text/css" href="../css/BarChart.css" rel="stylesheet" />

    <!-- JIT Library File -->
    <script language="javascript" type="text/javascript" src="../../jit-yc.js"></script>

    <!-- Example File -->
    <script language="javascript" type="text/javascript" src="example1.js"></script>
</head>

<body onload="init();">
<div id="container">

    <div id="left-container">



        <div class="text">
            <h4>
                Bar Chart Example
            </h4>

            A static vertical Bar Chart example with gradients. The Bar Chart displays tooltips when hovering the stacks. <br /><br />
            Click the Update button to update the JSON data.

        </div>
        <ul id="id-list"></ul>
        <a id="update" href="#" class="theme button white">Update Data</a>


        <div style="text-align:center;"><a href="example1.code.html">See the Example Code</a></div>
    </div>

    <div id="center-container">
        <div id="infovis"></div>
    </div>

    <div id="right-container">

        <div id="inner-details"></div>

    </div>

    <div id="log"></div>
</div>
</body>
</html>

Re: Injecting Javascript into view (Beginner Question)

You are using the assets pipeline,  so you'd do this in your document <head>

<%= stylesheet_link_tag    "application", :media => "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>

then get rid of

    <link type="text/css" href="../css/base.css" rel="stylesheet" />
    <link type="text/css" href="../css/BarChart.css" rel="stylesheet" />

    <!-- JIT Library File -->
    <script language="javascript" type="text/javascript" src="../../jit-yc.js"></script>

    <!-- Example File -->
    <script language="javascript" type="text/javascript" src="example1.js"></script>


The fist line will grab ALL the css in app/assets/stylesheets
The second line will grab all the javascripts in app/assets/javascripts
The third line will generate the authenticity token for posts,  you can leave it out of you are not using forms that post on the page.

Your app/assets should look like:
app/assets/javascripts/application.js
app/assets/javascripts/jit-yc.js
app/assets/javascripts/example1.js

app/assets/stylesheets/application.css
app/assets/stylesheets/base.css
app/assets/stylesheets/BarChart.css

application.js is your manifest for the assets pipeline,  it should stay as it was when you first generated your app

same with application.css, it's the stylesheet manifest

Then run:
bundle exec rake assets precompile

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Injecting Javascript into view (Beginner Question)

Sorry, I type too fast


Then run:
bundle exec rake assets:precompile

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: Injecting Javascript into view (Beginner Question)

All up and running now, thank you for your help!

Last edited by ChrisL1200 (2012-02-15 10:39:54)