0

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?

user1238784
  • 2,250
  • 3
  • 22
  • 41

3 Answers3

2

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>
Asons
  • 84,923
  • 12
  • 110
  • 165
1

You are not calling the function using ()

<div class="grayableDiv" onmouseover ="DoGrayEffectIn()" onmouseout="DoGrayEffectOut()">
Nandita Sharma
  • 13,287
  • 2
  • 22
  • 35
1

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>
Community
  • 1
  • 1
lewis
  • 23
  • 4