user1238784
user1238784

Reputation: 2440

Change the style of a div with javascript and jquery

In my source I have: In the style section:

<head>
        <style>
               .grayableDiv{background-color:transparent}
        </style>
    </head>

<script>
            function DoGrayEffectIn()
            {
                $('.grayableDiv').css('background-color', 'Gray');

            }
            function DoGrayEffectOut()
            {
                $('.grayableDiv').css('background-color', 'Transparent'); 
            }
       </script>

<div class="grayableDiv" onmouseover ="DoGrayEffectIn" onmouseout="DoGrayEffectOut">

But I cannot see the effect when going with the mouse over the div. What am I doing wrong. Is it possible to mix jquery and javascript in this way?

Upvotes: 0

Views: 45

Answers (3)

Asons
Asons

Reputation: 87191

You need to add parenthesis () to your event handlers so their functions gets called.

Should be onmouseover ="DoGrayEffectIn()", not onmouseover ="DoGrayEffectIn"

Stack snippet

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<head>
  <style>
    .grayableDiv {
      background-color: transparent
    }
  </style>
</head>

<script>
  function DoGrayEffectIn() {
    $('.grayableDiv').css('background-color', 'Gray');
  }

  function DoGrayEffectOut() {
    $('.grayableDiv').css('background-color', 'Transparent');
  }
</script>

<div class="grayableDiv" onmouseover="DoGrayEffectIn()" onmouseout="DoGrayEffectOut()">div</div>


A better practice for attaching JavaScript to the front-end of a website is to separate it from the markup, often referred as unobtrusive javascript.

Stack snippet

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<head>
  <style>
    .grayableDiv {
      background-color: transparent
    }
  </style>
</head>

<script>
  $(document).ready(function() {
    $('.grayableDiv')
      .mouseover(function() {
        $(this).css('background-color', 'Gray');
    }).mouseout(function() {
        $(this).css('background-color', 'Transparent');
    });
  });
</script>

<div class="grayableDiv">div</div>

Upvotes: 2

lewis
lewis

Reputation: 23

Another cleaner way without mixing the JavaScript with the Html

<script>
$(document).ready(function(){
    $(".grayableDiv").mouseover(function(){
        $(".grayableDiv").css("background-color", "gray");
    });
    $(".grayableDiv").mouseout(function(){
        $(".grayableDiv").css("background-color", "transparent");
    });
});
</script>

Upvotes: 1

Nandita Sharma
Nandita Sharma

Reputation: 13407

You are not calling the function using ()

<div class="grayableDiv" onmouseover ="DoGrayEffectIn()" onmouseout="DoGrayEffectOut()">

Upvotes: 1

Related Questions