Skip to content Skip to sidebar Skip to footer

How To Assign Event To Variable In Js

Hello I have a pretty basic question about events in JS. Can I do something like: var myobj = { }; document.getElementById('myid').onmousemove = function (e) { myobj.e = e; } ..

Solution 1:

Yes, you could do something like this

var myEvents = [];
var myDiv = document.getElementById("myDiv");
var infoDiv = document.getElementById("info");

functionlogEvent(e)
{
    e.preventDefault(); // prevent default behaviour if needed
    myEvents.push(e); // Store event info
}

myDiv.onmousemove = myDiv.onmousedown = myDiv.onmouseup = logEvent; 

// Set a timer for looping through the events
gameTimer = setInterval(function() {
    // Loop through eventswhile (myEvents.length>0)
    {
        ev = myEvents.shift();
        // Display event info
        infoDiv.innerHTML = ev.type + " " + infoDiv.innerHTML; 
    }
}, 100)​
​

DEMO

Solution 2:

Ah ha, your edit made things a lot clearer. Here's what you should be using:

<p id="info"></p><canvas id="can" width="400px" height="400px" style="border: 2px solid red"></canvas>

var can = document.getElementById('can'), info = document.getElementById('info');
function eventHandler(e) {
    info.innerHTML = e.type;
}
can.onclick = can.onmouseover = can.onmouseout = can.oncontextmenu = eventHandler;

Basically, you're assigning myobj.e in the event handler, but use it outside of the event handler. myobj.e will be undefined until the event fires. What you want is simply to do all event-related functionality in the event callbacks.

You might want to learn a bit about asynchronous programming. Events fire asynchronously -- you don't know when the user will move the mouse.

Solution 3:

The event is dispatched asynchronously when the factors leading to its dispatch occur. You need to update the DOM (HTML) in the event handler.

var myobj = {};

document.getElementById('myid').onmousemove = function (e) {
  document.getElementById('info').innerHTML = e.type;

  myobj.e = e; // not sure if you need this, not required for the update
};

Update:

I see that you listen to various events. To keep your code DRY (don't repeat yourself), create a function which updates the "info" element and use it as a handler for all the events.

var updateInfo = function (e) {
  document.getElementById('info').innerHTML = e.type;
};

var target = document.getElementById('can');
target.onmouseover = updateInfo;
target.onmousemove = updateInfo;
target.onmouseout = updateInfo;
// ...

Post a Comment for "How To Assign Event To Variable In Js"