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.

I would appreciate any help with this.

share|improve this question
what is $('#page') reffering to? make sure $('#page') is a valid html element – Thariama Oct 17 '12 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 – sisko Oct 17 '12 at 10:38
is it available to the time of point when you try to access it? – Thariama Oct 17 '12 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 – sisko Oct 17 '12 at 10:45
you may test it easily just log $('#page') to console right before you access it – Thariama Oct 17 '12 at 10:50

1 Answer

up vote 1 down vote accepted

@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!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.