Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call js function without event

How can I just call a js function from within an html file, with no event trigger? I want to have code like:

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="jquery.flot.js"></script>
<script src="chart.js"></script>

<title>
</title>
</head>

<body>

<div id="chart1" style="width:600px;height:300px"></div>

show_graph({{ chart_type }}, {{ data }}, {{ options }});

</body>

</html>

but this just results in the function call being printed to the screen, instead of the function actually being executed.

e.g. I'm getting show_graph(bar, [[1, 2000], [2, 50], [3, 400], [4, 200], [5, 5000]], ['Foo']);

What do I do?

EDIT:

I appreciate the feedback, but I tried wrapping it in a script tag and got an "invalid number of parameters" error.

the javascript is:

function show_graph(charttype, data, options){

    var chart_options = {
        series: {
            charttype: {
                show: true
            }
        }
    }

    var plot = $.plot($("#chart1"), [data], [chart_options]);
}

so I suppose the real question is "why am I getting an "invalid number of parameters" error when I'm passing 3 parameters and accepting 3 parameters?"

like image 354
Colleen Avatar asked Aug 23 '11 22:08

Colleen


People also ask

Can I call function from JS?

How to call a function in JavaScript. Calling a function (aka method) in JavaScript is similar to any other programming language that uses a C-like syntax. Simply call the function by name, then pass in any required parameters in a comma delimited list enclosed in parenthesis.

Can a function be executed without being called?

It is also common to say "call upon a function", "start a function", or "execute a function". In this tutorial, we will use invoke, because a JavaScript function can be invoked without being called.

How do I call a JavaScript function from HTML?

To include our JavaScript file in the HTML document, we have to use the script tag <script type = "text/javascript" src = "function.


2 Answers

Yet another answer:

<script type="text/javascript">
    (function() {
        // The following code will be enclosed within an anonymous function
        var foo = "Goodbye World!";
        document.write("<p>Inside our anonymous function foo means '" + foo + '".</p>');
    })(); // We call our anonymous function immediately
</script>
like image 134
Rafael Herscovici Avatar answered Oct 13 '22 01:10

Rafael Herscovici


Wrap it in <script> tags:

<body>

<div id="chart1" style="width:600px;height:300px"></div>

<script type="text/javascript">
    show_graph({{ chart_type }}, {{ data }}, {{ options }});
</script>

</body>

...though I don't know how the template factors in. I imagine it will render the same.

like image 31
user113716 Avatar answered Oct 13 '22 00:10

user113716