pwnchaurasia
pwnchaurasia

Reputation: 1499

Trigger mousemove event using Jquery or Javascript

Hi I know we can trigger click event. but I want to know that can we trigger mousemove event without any actual mouse movement by user.

Description :

I want to show a message when user select something. On canvas, my canvas is of full height and width, when user click on a button the canvas shows up. When user do mouse movement he see a message "Click and drag on any part of the web page". This message follows the mouse movement of the user.

What I want to do:

When user click the button he should see the message that "Click and drag on any part of the web page". and message must follow wherever user moves the mouse.

Problem :

User is not able to see the message after click until he/she moves his mouse.

Code:

      function activateCanvas() {
           var documentWidth = jQ(document).width(),
           documentHeight = jQ(document).height();
        
                 jQ('body').prepend('<canvas id="uxa-canvas-container" width="' + documentWidth + '" height="' + documentHeight + '" ></canvas><form method="post" id="uxa-annotations-container"></form>');

    canvas = new UXAFeedback.Canvas('uxa-canvas-container', {
        containerClass: 'uxa-canvas-container',
        selection: false,
        defaultCursor: 'crosshair'
    });


  jQ(function() {
        var canvas = jQ('.upper-canvas').get(0);
        var ctx = canvas.getContext('2d');
        var x,y;

        var tooltipDraw = function(e) {

            ctx.save();
            ctx.setTransform(1, 0, 0, 1, 0, 0);
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.restore();

            x = e.pageX - canvas.offsetLeft;
            y = e.pageY - canvas.offsetTop;
            var str = 'Click and drag on any part of the webpage.';

            ctx.fillStyle = '#ddd';
            ctx.fillRect(x + 10, y - 60, 500, 40);
            ctx.fillStyle = 'rgb(12, 106, 185)';
            ctx.font = 'bold 24px verdana';
            ctx.fillText(str, x + 20, y - 30, 480);

        };

        canvas.addEventListener('onfocus',tooltipDraw,0);
        canvas.addEventListener('mousemove',tooltipDraw,0);

        canvas.addEventListener('mousedown', function() {
            canvas.removeEventListener('mousemove', tooltipDraw, false);
            ctx.save();
            ctx.setTransform(1, 0, 0, 1, 0, 0);
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.restore();
        }, false);



       });
  }

        jQ('body').on('click', '.mood_img_div', function() {
    // alert("soemthing");
      toggleOverlay();
       activateCanvas();
       });

I have made a function which is called after click but the message is not visible. Is there any way to call it for the first time with message and show is everytime when user uses mouse.

I have replaced jQuery with jQ because I am making my own plugin(this is not causing the problem)

Upvotes: 26

Views: 44005

Answers (3)

Andrii Verbytskyi
Andrii Verbytskyi

Reputation: 7621

A good native approach is to use dispatchEvent method on EventTarget.

It dispatches an Event at the specified EventTarget, invoking the affected EventListeners in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent().

Try

// 1. Add an event listener first
canvas.addEventListener('mousemove', tooltipDraw, 0);

// 2. Trigger this event wherever you wish
canvas.dispatchEvent(new Event('mousemove'));

In your case it should trigger mousemove event on canvas element.

(Triggering events in vanilla JavaScript article can be also useful):

var elem = document.getElementById('elementId');

elem.addEventListenter('mousemove', function() {
  // Mousemove event callback
}, 0);

var event = new Event('mousemove');  // (*)
elem.dispatchEvent(event);

// Line (*) is equivalent to:
var event = new Event(
    'mousemove',
    { bubbles: false, cancelable: false });

jQuery:

Try this with jQuery trigger method:

 $('body').bind('mousemove',function(e){   
    // Mousemove event triggered!
});
$(function(){
    $('body').trigger('mousemove');
});

OR (if you need triggering with coords)

event = $.Event('mousemove');

// coordinates
event.pageX = 100;
event.pageY = 100; 

// trigger event
$(document).trigger(event);

OR Try using .mousemove() jQuery method

Upvotes: 28

Alexander Zabyshny
Alexander Zabyshny

Reputation: 91

let coordX = 0; // Moving from the left side of the screen
let coordY = window.innerHeight / 2; // Moving in the center

function move() {
    // Move step = 20 pixels
    coordX += 20;
    // Create new mouse event
    let ev = new MouseEvent("mousemove", {
        view: window,
        bubbles: true,
        cancelable: true,
        clientX: coordX,
        clientY: coordY
    });

    // Send event
    document.querySelector('Put your element here!').dispatchEvent(ev);
    // If the current position of the fake "mouse" is less than the width of the screen - let's move
    if (coordX < window.innerWidth) {
        setTimeout(() => {
            move();
        }, 10);
    }
}

// Starting to move
move();

Upvotes: 9

Kaiido
Kaiido

Reputation: 136578

Albeit it is probably possible to mimic such an event as shown in Andrii Verbytskyi's answer, most of the time, when you want to do it, it is because of an "X-Y problem".

If we take OP's case for instance, here we absolutely don't need to trigger this mousemove event.

Pseudo-code of current implementation :

function mousemoveHandler(evt){
    do_something_with(evt.pageX, e.pageY);
}
element.addEventListener('mousemove', mousemoveHandler)

function clickHandler(evt){
    do_something_else();
}
element.addEventListener('click', clickHandler);

And what we want is to also call do_something_with in the click handler.

So OP spends some time to find a way to trigger a fake mousemove, spends another amount of time trying to implement it, while all that is needed is to add a call to do_something_with in clickHandler.

Both mousemove and click events have these pageX and pageY properties, so the event can be passed has is, but in other case, we could also just want to pass it with a fake object containing required properties.

function mousemoveHandler(evt){
    do_something_with(evt.pageX, evt.pageY);
}
element.addEventListener('mousemove', mousemoveHandler)

function clickHandler(evt){
    do_something_else();
    do_something_with(evt.pageX, evt.pageY);
}
element.addEventListener('click', clickHandler);
// here we won't have pageX nor pageY properties
function keydownHandler(evt){
    do_something_else();
    // create a fake object, which doesn't need to be an Event
    var fake_evt = {pageX: someValue, pageY: someValue};
    do_something_with(fake_evt.pageX, fake_evt.pageY);
}
element.addEventListener('keydown', keydownHandler);

Note : you are mixing jQuery.on and element.addEventListener, so you might need to pass the originalEvent property of the jQuery event object.

Upvotes: 1

Related Questions