j. hol
j. hol

Reputation: 31

not sure why .css() wont change div qualities

I'm trying to use jQuery to change the value of the div 'dog' from blue (CSS) to red (javascript css code), but the javascript seems to not be functioning. CSS, JavaScript and jQuery are all linked properly (have checked).

HTML CODE:

 <!DOCTYPE html>
 <html>
  <head>
   <title></title>
   <link rel="stylesheet" type="text/css" href="style.css">
   <script  src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>       
   <script type="text/javascript" src="jquery-3.2.0.min.js"></script>
   <script type="text/javascript" src="script.js"></script>
  </head>
  <body>
   <div id="dog"></div>
  </body>
 </html>

CSS CODE:

#dog {
  background-color: blue;
  height: 200px;
  width: 200px;
}

JAVASCRIPT (jQuery) CODE:

$("#dog").css("background-color", "red");

Upvotes: 1

Views: 57

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56453

but the javascript seems to not be functioning. CSS, JavaScript and jQuery are all linked properly (have checked).

Ensure that you encapsulate the javascript within a $( document ).ready(). This should solve the problem if the script is loaded in the head element, where the HTML document has not been loaded fully yet.

However, an alternative solution is to use the script tag within the body element.

Example:

<!DOCTYPE html>
<html>
   <head>
     <title></title>
     <link rel="stylesheet" type="text/css" href="style.css">
     <script  src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery
.min.js"></script>       
     <script type="text/javascript" src="jquery-3.2.0.min.js"></script>
     <script type="text/javascript" src="script.js"></script>
     <style>
      #dog {
         background-color: blue;
         height: 200px;
         width: 200px;
       }
     </style>
   </head>
   <body>
     <div id="dog"></div>
     <script>
       $("#dog").css("background-color", "red");
     </script>
   </body>
</html>

Upvotes: 2

Harsheet
Harsheet

Reputation: 628

do this in your js file -

window.onload = function () {
    $("#dog").css("background-color", "red");
}

The reason is this -

window.onload - it is called after all DOM, JS files, Images, Iframes, Extensions and others completely loaded. This is equal to $(window).load(function() {});

As you have a seperate js file, and you want the style to be changed when the page is loaded, so you have to do this.

For more understanding, you can refer this - Difference between onload and window.onload

Upvotes: 0

Related Questions