amypellegrini
amypellegrini

Reputation: 1026

jQuery doesn't work on IE

I have the following jQuery script, which is actually being ignored by Internet Explorer (7 and 8). It works OK in FF and Chrome.

<script type="text/javascript" language="javascript">
    $("body").addClass("newclass");
</script>

It's very simple, yet I don't know for what reason IE ignores it. Know that the code is loaded as dynamic content with JAVA (which shouldn't be a problem since the rest of the scripts work). I tried to call tha script as a function in a external file, but nothing happens either. Can anyone help me to understand where is my error? Or help me to understand IE?

Upvotes: 4

Views: 8470

Answers (3)

Spudley
Spudley

Reputation: 168685

Wrap it in a $(document).ready(function(){ ... });

This way, JQuery will only run it once the page has full loaded.

If you don't do this, the code will be executed as soon as it can be, which may be before the DOM has loaded, so you may not have a body element to add the class to.

The fact that some browsers work and others don't implies that different browsers (a) load the page at different speeds, and/or (b) perform initial loading tasks in a different order. But you shouldn't need to worry about that. Just call $.ready() and it'll all be done in the right order for you by JQuery.

Upvotes: 0

Paul Spencer
Paul Spencer

Reputation: 1385

Or perhaps in the 'ready' event of the document would be better

$(document).ready(function() {
  $('body').addClass('newclass');
});

Upvotes: 7

Belinda
Belinda

Reputation: 1231

I'm sure that you would have issues in Firefox and Chrome as well if this was the issue but try

$(function () {
    $('body').addClass('newclass');
});

just to be sure that it is called after the document is loaded. Maybe IE needs that.

Upvotes: 0

Related Questions