-1

I have two css selectors linked up to an html element. Onmousedown javascript is supposed to change the class to 'closeMenuButtonActive' and onmouseup it should wait 500ms and then change the class name to 'closeMenuButtonNotActive'. For some reason this code isn't working correctly! I tried doing alert(this.className); to see what was going on, the alert said the correct closeMenuButtonNotActive. The strange part is that I looked at the element in the inspector and the class name hadn't changed! Here is my inline javascript code:

<div id="closeMenuButton" class="closeMenuButtonNotActive" onmousedown="this.className = 'closeMenuButtonActive';" onmouseup="window.setTimeout(function(){this.className = 'closeMenuButtonNotActive';},500);">
www139
  • 105
  • 10

2 Answers2

4

That's because this is refering to window on this function:

window.setTimeout(function() {
  // Wrong this
  this.className = 'closeMenuButtonNotActive';
},500);

Instead you could do

 var elem = this;
 window.setTimeout(function() {
  elem.className = 'closeMenuButtonNotActive';
},500);

Of if you don't want to pollute the global scope:

(function(elem) {
   window.setTimeout(function() {
    elem.className = 'closeMenuButtonNotActive';
  },500);
)(this);

Anyway, to prevent further problems that are hard to debug, you should really consider at least using a function in the HTML <div onmouseup="doStuff(this)"> and define doStuff from the javascript code. Or even better, add the mouse events listeners directive from the code.

Community
  • 1
  • 1
floribon
  • 19,175
  • 5
  • 54
  • 66
2

You should call you function with "bind" to keep the scope of "this".

window.setTimeout(
function(){
    this.className = 'closeMenuButtonNotActive';
}.bind(this),
500);
Yoann Augen
  • 1,966
  • 3
  • 21
  • 39