1

I'm learning JavaScript and I've got a question for you guys. The thing is that I'm trying to wrap my head around some event handlers, but while doing so I've come to realize that there is something that I don't understand about nodes.

I have this code that works fine when I use jQuery:

var canvas = $('#cvs');

canvas.mousemove(function(e){
     var pageCrds = '('+ e.pageX +', ' + e.pageY +')';

     var b = document.getElementById("first");
     b.firstChild.nodeValue = "(e.pageX, e.pageY) - "+ pageCrds;   
});

but this code is not working:

var canvas = document.getElementById('cvs');

canvas.mousemove(function(e){
    var pageCrds = '('+ e.pageX +', ' + e.pageY +')';

    var b = document.getElementById("first");
    b.firstChild.nodeValue = "(e.pageX, e.pageY) - "+ pageCrds;   
});

The HTML that I am using is the same in both cases:

 <canvas id="cvs" width="150" height="150"></canvas>
    <div id="first">Move mouse over canvas.</div>
       <p id="one"></p>    
       <p id="two"></p>

Can anybody shed some light as to why the jQuery-version works and not the one in pure JavaScript? Obviously, I would like to be able to do my task in pure JavaScript as well as in jQuery.

2 Answers 2

4

When not using jQuery, you'll need to use onmousemove

canvas.onmousemove = function(e){
    var pageCrds = '('+ e.pageX +', ' + e.pageY +')';

    var b = document.getElementById("first");
    b.firstChild.nodeValue = "(e.pageX, e.pageY) - "+ pageCrds;   
};
Sign up to request clarification or add additional context in comments.

3 Comments

or better addEventListener().
Yeah addEventListener() would be the recommended way. I just posted a minimal-change fix.
jQuery selectors return facades on the actual document objects, so document.getElementById and $(...) are not the same thing
1

the function canvas.mousemove() is jquery, you have to use non-jquery equivalent canvas.onmousemove = function(e){} or canvas.addEventListener("mousemove", function(e){}, useCapture);. The useCapture value replaces the return value from the handler and determines whether the event continues to 'bubble'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.