0

I have the following code, the problem with that is, if you right click and select 'Copy' on other elements on the page before setTimeout() ends, the previously clicked element won't change its style, because of the global variable being assigned with new element value.

How to modify this so setTimeout() completes its task for the called element?

var whichNode;
var contextMenu = new gui.Menu()

contextMenu.append(new gui.MenuItem({
    label: 'Copy',
    click: function() {
        whichNode.style.color = '#40c4ff'
        setTimeout(function(){ whichNode.style.color = 'inherit' }, 1000)
    }
}))

document.addEventListener('contextmenu', function(e) {
    e.preventDefault;
    whichNode = e.srcElement;
    contextMenu.popup(e.x, e.y)
})
Hacketo
  • 4,978
  • 4
  • 19
  • 34
Fiat Pax
  • 417
  • 6
  • 18

1 Answers1

1

You should simply mantain a copy of the reference to whichNode. Maybe doing:

contextMenu.append(new gui.MenuItem({
label: 'Copy',
click: function() {
  var nodeCopy = whichNode;
  nodeCopy.style.color = '#40c4ff'
  setTimeout(function(){ nodeCopy.style.color = 'inherit' }, 1000)
}
}))

is enough.

AndreaBogazzi
  • 14,323
  • 3
  • 38
  • 63
  • Ahh.. I did the same before except I put the new variable in setTimeout()... This works thanks! – Fiat Pax Jan 14 '15 at 14:00
  • 1
    Be careful not all browser support additional paremteres in setTimeout. check http://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-to-a-settimeout-callback secondo answer, secondo comment. Also calling the anonymous function is not a standard. – AndreaBogazzi Jan 15 '15 at 11:22