0

I am trying to load a JavaScript file for my module. The javascript code should execute and dynamically apply some CSS styling.

However, my jQuery is not having any effect. Plain vanilla JavaScript code works but not my jQuery code.

I am loading my JavaScript with the following code:

drupal_add_js(drupal_get_path('module', 'my_module') .'/js/mycode.js', 'file');

I'm applying this code outside of any function but loaded it in hook_node_view when the $view_mode is full.

And the following is my javascript:

(function ($) {

    alert('RESPONDING!');

    $('#page').css('background', 'red')

    alert('RESPONDING-2!');


    jQuery('body').click(
        function () {
            alert('clicked!');
        }
    );

})(jQuery);

Nothing $/jQuery tagged works but both alert statements work.

5
  • what is $('#page') reffering to? make sure $('#page') is a valid html element Commented Oct 17, 2012 at 10:35
  • div#page is a valid element. I am actually pasting the same code into Chrome's console and it works as expected Commented Oct 17, 2012 at 10:38
  • is it available to the time of point when you try to access it? Commented Oct 17, 2012 at 10:40
  • That's where I was a bit unsure. There is no real reason why it could not be available but, just in case, I used hook_node_view and only load the js when the page is fully loaded Commented Oct 17, 2012 at 10:45
  • you may test it easily just log $('#page') to console right before you access it Commented Oct 17, 2012 at 10:50

1 Answer 1

1

@Thariama:

Thanks for all your input and ideas.

Your suggestion to console.log($('#page')) was very instructive. I realized something was seriously wrong when the output came out entirely empty. It go me thinking and I decided to try relocating the code to "the bottom of the page".

With the following modified code:

drupal_add_js(drupal_get_path('module', 'my_module') .'/js/mycode.js', array('type' => 'file', 'scope' => 'footer'));

My $/jQuery tagged code now executes.

Thanks!

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.