1

I guess this is really simple, but I can't get it to work. I have a script in my help.js in app/assets/javascript.

This is loaded and if I add an alert() it is run, but when I try to call the javascript (jquery click()) nothing happens. If I have the javascript-code in the page it works if at the bottom of the page.

I guess the includes from the assets are put at the start of the page, and then my script won't work. So...

  1. Am I completely worthless at writing javascripts?
  2. Should the javascript be placed at the end, and how would that be done when requiring it from assets without moving the complete javascript_include_tag? (I guess I could exclude it from applications and load it separately, but it feels wrong).
  3. It feels very strange that this shouldn't work, so where did I go wrong?

help.js

$('.clickme').click(function() {
  $('#working').show();
  var htmlStr = this.getAttribute('data-message');
  $('#helper_box').html(htmlStr);
  $('#helper_box').toggle('slow', function() {
    // Animation complete.
    $('#working').hide();
  });
});

index.html.erb

<div class="clickme" data-message="Something...">
  <%= image_tag("question_mark.png", :alt => "helper") %><br>
</div>
2
  • any errors on firebug/js console after clicking? I guess you are not including jquery in application.js file or requiring jquery library after help.js file. Paste the content of application.js file Commented Feb 23, 2012 at 11:47
  • Friend you have to ensure that your script must be executed after DOM is ready.So @Gonzalo Quero is corrent. Commented Feb 23, 2012 at 12:42

2 Answers 2

5

Events in jQuery should be added after the document is completely loaded. Have you tried using

$(document).ready(function() {
  $('.clickme').click(function() {
    $('#working').show();
    var htmlStr = this.getAttribute('data-message');
    $('#helper_box').html(htmlStr);
    $('#helper_box').toggle('slow', function() {
     // Animation complete.
     $('#working').hide();
    });
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Sweet. That did the trick. As I thought it was something easy, as pretty much everything is when you now it. Thanks Gonzalo.
5

I think your code is correct. I checked it at http://jsfiddle.net/Dd46n/ I guess the help.js is loading before the jQuery library file.

1 Comment

Yupp. That was the problem. Thanks for the heads up.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.