how should i call a javascript function into a kohana view?
i am having a simple kohana view, and a javascript that makes a countdown of 30 minutes. I hava put the javascript file into a directory /media m and its name is countdown.js . My problem is: how can i call that javascript? Form the view? Or from the controller to be displayed in the view? and how exactly may i address in a controller or a view that js function or functions?
thank you
the countdown js:
var javascript_countdown = function () { var time_left = 10; //number of seconds for countdown var output_element_id = 'javascript_countdown_time'; var keep_counting = 1; var no_time_left_message = 'No time left for JavaScript countdown!';
function countdown() {
if(time_left < 2) {
开发者_运维技巧 keep_counting = 0;
}
time_left = time_left - 1;
}
function add_leading_zero(n) {
if(n.toString().length < 2) {
return '0' + n;
} else {
return n;
}
}
function format_output() {
var hours, minutes, seconds;
seconds = time_left % 60;
minutes = Math.floor(time_left / 60) % 60;
hours = Math.floor(time_left / 3600);
seconds = add_leading_zero( seconds );
minutes = add_leading_zero( minutes );
hours = add_leading_zero( hours );
return hours + ':' + minutes + ':' + seconds;
}
function show_time_left() {
document.getElementById(output_element_id).innerHTML = format_output();//time_left;
}
function no_time_left() {
document.getElementById(output_element_id).innerHTML = no_time_left_message;
}
return {
count: function () {
countdown();
show_time_left();
},
timer: function () {
javascript_countdown.count();
if(keep_counting) {
setTimeout("javascript_countdown.timer();", 1000);
} else {
no_time_left();
}
},
init: function (t, element_id) {
time_left = t;
output_element_id = element_id;
javascript_countdown.timer();
}
};
}();
//time to countdown in seconds, and element ID javascript_countdown.init(3673, 'javascript_countdown_time');
You can use kohana html helpers. In your controller function or your view file, you can have it like this :
echo html::script('media/countdown.js');
Place the echo
statement after the html element with id "javascript_countdown_time". Before the closing </body>
if possible.
...
<div id="javascript_countdown_time"></div>
...
<script src="/media/countdown.js"></script>
</body>
You could do what @erickb said, or you could do this in your
view (php)
<script src="media/countdown.js"></script>
make sure that countdown.js is loaded when the page is displayed in your browser [ use firebug or developer panel in chrome to verify it was loaded. ]
Wherever you wanted to call the functions from , just call it.. Let us know how it went..
精彩评论