mouseWheel and other callback functions not working in Instance Mode

After converting my code into instance mode, all the callback functions I had in place are not working anymore: for example mouseWheel, mousePressed, windowResized and so on.
Should those functions reside inside the instance class scope or outside?
Thank you for any help!

1 Like

Can you please post a MCVE?

Inside.

Solved thanks, I assigned the functions to the sketch object passed inside the p5 constructor and then they worked. Something like sketch.windowResized() { }

1 Like

Or something like this: sketch.windowResized = function () { } :wink:

2 Likes

Yes actually that’s the correct solution, thanks

Would you be willing to post an example of this? Struggling to get mouseWheel working in instance mode.

http://p5js.SketchPad.cc/sp/pad/view/ro.C9V0wpmLEMeNC4/latest

1 Like

Thank you. Still seem to be having issues getting the variable to be recognized within the instance.


var canvasDiv = document.getElementById('container');
var width = canvasDiv.offsetWidth;
var height = canvasDiv.offsetHeight;
var pos = 25;

var s = function( p ) {
 
    
  p.setup = function() {
    p.createCanvas(width, height);
  };

  p.draw = function() {
    p.rect(pos,100,50,50);
  };

 
};

var myp5 = new p5(s,"container");

function mouseWheel(event) {
  print(event.delta);
  //move the square according to the vertical scroll amount
  pos += event.delta;
  //uncomment to block page scrolling
  //return false;
}

window.onresize = function () {
    location.reload();
}```

The code from my link is in “global” mode, not “instance”! :globe_with_meridians:

Obviously, a global-scoped mouseWheel() won’t be recognized as a callback function by a sketch in “Instance” mode! :telephone_receiver:

Just follow the same approach you’re already doing for callbacks setup() & draw(): :bulb:

function mouseWheel(event) { :arrow_right: p.mouseWheel = function (event) {

1 Like

Perfect. Thank you. Leaving the final example here.

var canvasDiv = document.getElementById('container');
var width = canvasDiv.offsetWidth;
var height = canvasDiv.offsetHeight;
var pos = 25;

var s = function( p ) {
 
    
  p.setup = function() {
  
    p.createCanvas(width, height);
  };

  p.draw = function() {
  	p.background(0);
    p.rect(pos,100,50,50);
  };

  p.mouseWheel = function (event) {
  p.print(event.delta);
  //move the square according to the vertical scroll amount
  pos += event.delta;
  //uncomment to block page scrolling
  //return false;
}
 
};

var myp5 = new p5(s,"container");



window.onresize = function () {
    location.reload();
}