2

This is what my template looks like:

{% extends 'typer/base.html' %}
{% load url from future %}

{% load staticfiles %}

{% block title %}{{ p_name }}{% endblock %}

{% block body_block %}
<script type='text/javascript'
src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script>
    $('#user_passage_text').on('keyup', function(e) {
        if ( e.which === 13 ) {
        var time = (new Date()).getTime() - $(this).data('time');
        $(this).data('time', 0);
        console.log('Time passed : ' + time + ' milliseconds');

        }else if ( !$(this).data('time') ){
            $(this).data('time', (new Date()).getTime());
        }
    });
</script>

    <h1>{{ p_name }}</h1>
    <p>This passage is {{ p_wlength }} words, {{ p_clength }} characters long.</p>
    {% if passage %}
        <p><blockquote>{{ p_text_body|linebreaksbr }}</blockquote></p>

    {% else %}
        The specified text {{ p_name }} does not exist!
    {% endif %}

    <p>
        Begin typing to start the test.
    </p>
    <textarea id="user_passage_text"></textarea>


{% endblock %}

All I want for this to do is print a message to the console to check that the function is working. The reason I'm confused about it not working is that I can run it on http://jsfiddle.net/d8c4z300/ perfectly fine. So why does the message print there but not when I run the django template?

2
  • 1
    Are there any errors messages in your browser? How does the out coming html look like? Commented Jan 1, 2015 at 11:20
  • There aren't any error messages. The out coming html looks like this: pastebin.com/hm1Ty7Lu. Commented Jan 1, 2015 at 11:32

1 Answer 1

4

you need $(function(){ ... }) (or $( document ).ready(function() { ... }); which is equal, only longer) around your js code:

so:

$(function(){

  $('#user_passage_text').on('keyup', function(e) {
    if ( e.which === 13 ) {
    var time = (new Date()).getTime() - $(this).data('time');
    $(this).data('time', 0);
    console.log('Time passed : ' + time + ' milliseconds');

    }else if ( !$(this).data('time') ){
        $(this).data('time', (new Date()).getTime());
    }
  });

});

fiddle is working because you set it to onload which is almost equal to $(function(){ ... }) here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.