0

i Was trying to make a simple button which changes colour on mouse over using JavaScript and its not working so,help please.... html:

<head lang="en">
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="Button.css" />
<script type="text/javascript" src="Button.js"></script>
<title>BUTTON</title>
</head>
<body>
<div id="Button">PRESS ME</div>
</body>

JavaScript:

var Button = document.getElementById('Button');
Button.onmouseover(function(){
this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
});

CSS:

#Button{
width: 120px;
height : 30px;
position: fixed;
top: 100px;
left:300px;
border: 1px solid black;
background-color : rgba(0,0,255,0.3);
font-size : 25px;
}
Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
RatikBhat
  • 61
  • 11

2 Answers2

2

Change

 Button.onmouseover(function(){
   this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
 });

to

   Button.onmouseover = function(){
       this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
    };

Full example:

var Button = document.getElementById('Button');
Button.onmouseover = function () {
    this.style.backgroundColor = 'rgba(0,255,0,0.3)';
};
#Button {
    width: 120px;
    height : 30px;
    position: fixed;
    top: 100px;
    left:300px;
    border: 1px solid black;
    background-color : rgba(0, 0, 255, 0.3);
    font-size : 25px;
}
<div id="Button">PRESS ME</div>

JSFiddle demo: http://jsfiddle.net/n4j53jcu/

Miguel Mota
  • 20,135
  • 5
  • 45
  • 64
0

You're confusing two different paradigms of hooking events. onmouseover is a property you can assign a single function to, via assignment (not calling it). So you could do:

Button.onmouseover = function(){
    this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
};

var Button = document.getElementById('Button');
Button.onmouseover = function(){
  this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
};
#Button{
width: 120px;
height : 30px;
position: fixed;
top: 100px;
left:300px;
border: 1px solid black;
background-color : rgba(0,0,255,0.3);
font-size : 25px;
}
<div id="Button">PRESS ME</div>

But the modern way is to play nicely with others and not bludgeon any previous handler (which the above does), but just add to the handler list:

Button.addEventListener("mouseover", function(){
    this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
}, false);

var Button = document.getElementById('Button');
Button.addEventListener("mouseover", function(){
  this.style.backgroundColor  = 'rgba(0,255,0,0.3)';
}, false);
#Button{
width: 120px;
height : 30px;
position: fixed;
top: 100px;
left:300px;
border: 1px solid black;
background-color : rgba(0,0,255,0.3);
font-size : 25px;
}
<div id="Button">PRESS ME</div>

Of course, IE8 and earlier make that difficult, but you can use the function in this other answer if you need to support them.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875