Search code examples
javascriptnode.jswebkitsettimeout

Running setTimeout() for a Specific DOM Element


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)
})

Solution

  • 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.