fabrv
fabrv

Reputation: 382

$(document.body).css not working

I have been trying to change the background image of my HTML body with a .js but nothing happens. Do I need to put the Javascript code inside my HTML?

function plano1() {
    alert('you');
    $(document.body).css('background-image', 'url(img/planoSelected.png)');
}

This is the complete function I have been trying to do. Google Chrome shows the alert, but doesn't do the $(document.body). What am I supposed to do?

Notes: I use the function with a "onmouseover". I have already tried to use:

$('body').css('background-image', 'url(img/planoSelected_2.png)');

$("body").css('background-image', 'url(img/planoSelected_2.png)');

Upvotes: 0

Views: 1454

Answers (2)

Sergio Wizenfeld
Sergio Wizenfeld

Reputation: 492

The jQuery code should be called at the bottom of the page, above the closing body tag.

Load jQuery first:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function() {
        $('body').css('background-image', 'url(img/planoSelected_2.png)');
    });

</script>

Upvotes: 1

Broxzier
Broxzier

Reputation: 2949

The code is fine, but there are a few reasons why this might not work.

  1. Make sure the image paths are correct, relative to the script's location
  2. Is plano1 called?
  3. Make sure jQuery is actually loaded
  4. Make sure the DOM is ready when calling the function (use $(document).ready if not sure)
  5. Make sure there are no errors in the code before plano1 is called

If these things are all right, and it still doesn't work, check if your onmouseover is working at all. Simply alert or log something in the console.

Upvotes: 0

Related Questions