mousePressed method is launching prematurely in p5js - p5.js

I created the following function using p5.js and the mousePressed method is firing immediately when the page loads. It doesn't wait for me to click the button object to display a paragraph containing the ans variable.
What am I doing wrong?
function setup() {
var ans = generate();
var checkMe = createButton('Check Answer');
checkMe.mousePressed(createP(ans));
}

Let's take a closer look at this line:
checkMe.mousePressed(createP(ans));
This could be split into two lines:
var createPValue = createP(ans);
checkMe.mousePressed(createPValue);
In other words, you're calling the createP() function, and then passing the value returned (which is probably undefined) into the mousePressed() function. I'm surprised this doesn't cause an error in the JavaScript console.
Instead, what you want to do is pass a function as a value into the mousePressed() function. Since you need to use a parameter, you might do that this way:
function callCreateP(){
createP(ans);
}
checkMe.mousePressed(callCreateP);
Notice that callCreateP doesn't have parentheses () after its name when we pass it into the mousePressed() function. That's because we're using it as a value instead of directly calling it.
You could shorten that to this line:
checkMe.mousePressed(function(){ createP(ans); });

Related

Using random in JSP5

Does someone know how I can fix this problem?
var Arguments [2003,1002,3932,10203,2030,1828912,12912]
var Argument = Arguments[Math.floor(Math.random() * Arguments.length)]
Because of these variables, a random argument is always chosen at the beginning. However, if you are in the program and switch from page to page, it will keep the random value it had at the beginning. I want him to be constantly creating new values.
In the draw function I call the argument like this:
text(Argument, 300,180);
If I understand your question and the comments correctly, you need re-assign Argument to be a different random value each time you switch pages, such as this line every time it switchs:
Argument = Arguments[Math.floor(Math.random() * Arguments.length)];
You don't put var there every time. Give it a value in setup(), then re-assign it when you need another value.
Unless, of course, I completely missed your problem.
In p5.js there is a helpful function called random
so you could use it like this
var Arguments [2003,1002,3932,10203,2030,1828912,12912]
var Argument = Arguments[random(0, Arguments.length - 1)]
you can read more about it here
Make argument into a function.
var Arguments [2003,1002,3932,10203,2030,1828912,12912];
var Argument = function(){
return Arguments[ Math.floor( Math.random() * Arguments.length ) ];
}
text(Argument(), 300,180);
If you make a random selection in setup() it will only happen once in your whole script. Also, Don't choose variable names that might already be used by the system (I suspect "arguments" might be.
let args = [2003,1002,3932,10203,2030,1828912,12912];
let a;
function setup() {
createCanvas(400, 400);
a = random(args);
}
function draw() {
background(220);
textSize(30);
text(a,50,70);
}
function mousePressed() {
a = random(args);
}

Adobe Animate gotoAndStop for Movie clip

I created HTML5-canvas and added Rectangle like Movie (Movie1)
Then I created Animate for Movie1
But I don't know how works JS, when I try to stop Animate.
AS3 Action:Frame1
trace (this.Movie1);
this.Movie1.gotoAndStop(1);
How I need to write it on JS ?
I check different way but all of them doesn't work.
this.Movie1.gotoAndStop(1);
Movie1.gotoAndStop(1);
I opened console IE and saw
SCRIPT5007: Unable to get property 'gotoAndStop' of undefined or null reference
also I wrote second Example
this.stop();
alert(this.Movie1);// output: MovieClip (name=null)
//this.Movie1.gotoAndStop(1);
this.addEventListener('click', alertpopup);
function alertpopup(){
//this.Movie1.gotoAndStop(1);
alert(this.Movie1); // output: undefined ???
}
So, I decided this task only when I inserted code in generated HTML file at the end Function Init(). Something like this
var canvas, stage, exportRoot;
function init() {
// --- write your JS code here ---
canvas = document.getElementById("canvas");
exportRoot = new lib.ExAS3_Canvas();
stage = new createjs.Stage(canvas);
stage.addChild(exportRoot);
stage.update();
createjs.Ticker.setFPS(lib.properties.fps);
createjs.Ticker.addEventListener("tick", stage);
Update(exportRoot);
}
function Update(root){
<!-- write your code here -->
root.stop();
//this.Movie1.name = 'Movie1';
console.log("m=" + root.Movie1);
root.Movie1.stop();
root.Movie1.addEventListener('click', alertpopup);
function alertpopup(){
root.Movie1.gotoAndStop(1);
console.log("r=" + root.Movie1);
}
}
Why the code is not working from the IDE ?
I try to change this on my first frame on exportRoot and it works partially
//this.Movie1.stop(); // it doesn't work
//exportRoot.Movie1.stop(); // it doesn't work
this.Movie1.addEventListener('click', alertpopup);
var i = 0;
function alertpopup(){
i++;
if(i==2) i = 0;
exportRoot.Movie1.gotoAndStop(i);
}
I found that writing your code in the first frame gives a problem getting in touch with movieclips on the Stage (this.Movie1) - but putting the code in the second frame helps. Also I found, that the use of "this" inside a function sometimes gives the usual js-error: "this" refers to the function, and not to the object you are "inside" (Stage). Solve this problem by a variable "var that=this;" and use "that" instead of "this" inside the function.

trigger.io file.saveURL and looping

I am using the file.saveURL in a loop and its working good but I am seeing some strage things. Basically I loop over about 70 images and then grab the uri to them after they are saved and store that locally so I can then use it to display in the app
What happens is that once the loop is done I display the images out but randomly some of the images are the same. I have validated the correct URL is being passed but its as if and I don't know for sure but maybe the function is not done with the previous and is somehow overwriting it?
This makes the most sence because the issue usually happens with images right next to each other.
So I guess my question is, does the file.saveURL only work on a one to one aspect, like it has to by synchronous?
If that is the case what would be the recommended approach for looping over and saving these images.
Thanks!
EDIT
This is a basic sample (I have some conditional stuff in there but this is the main part)
I have the JSON object stored and I loop over it
$(data).each(function(i){
var slcval = 'speaker' + this.SID;
var imageID = 'simageid' + this.IMAGE;
var speakerImage = "http://mydomain.com/users/images/speakers/" + this.IMAGE;
//then I call the save url function
saveURLImage(speakerImage,slcval,'speaker',this.SID,imageID);
}
this loops over my images and calls the save image function that then does the save URL function
function saveURLImage(url,ID,type,extraVal,imageID){
forge.file.saveURL(url, function (file) {
forge.file.URL(file, function (url) {
var fileObject = JSON.stringify(url);
localStorage.setItem(ID, fileObject);
})
});
}
This is a simple version of it, I have some other parts that set some localstorage vars but this is the main call.
So my problem was a scoping issue
so if anyone else comes arrocss this I found this thred that helped out
Javascript: function in setTimeout and references
Basically what I did was creat a function that has an announmous function in it so the scope would be correct
function saveURLImage(url,ID,type,extraVal,imageID) {
(function() {
saveURLImageScoped(url,ID,type,extraVal,imageID)
})();
}
so the function name is still the same as before but I renamed the main function saveURLImageScoped and now it has its own variable scope

changing text inside element script

I have a script which contains 2 functions.
First function is responsible for creating a paragraph element inside existing div.
Second part of the script is a function which changes the predefined text (the text is predefined in the first function) triggered by onclick event.
HTML:
Change Text
<div id='box'></div>
Javascript:
var x, el;
window.onload = function createEl() {
x = document.getElementById('box');
el = document.createElement('p');
el.appendChild(document.createTextNode("Hello"));
x.appendChild(el);
}
function changeText() {
el.innerHTML = 'other text';
}
My question is: Is there any way to achieve the same result but do this without using global variables? I know there should be an option just to pass the variable from one function to another and then update it there, but I am not sure how to do this though
Just give the p tag an id and use document.getElementById to get it.

Is there a way to break out of event recursion in jQuery without using a global variable?

I have a form with 2 text inputs and 2 span controls. Normally, when textbox A is changed an event is fired to change span A, and when textbox B is changed, an event is fired to change span B.
However, in one particualar case I would like a change either textbox A or textbox B to update both span A and B. I tried wiring the events up to the corresponding controls in this case, but it didn't work because there is much state that is set up in the event building code (not to mention each event calls 'this', which would make the logic use the wrong control if it were fired from a different one than it was intended).
To make things easy, it would be best to pass a string (representing the other text input id) to the event handler at the time it is created, and then calling the change() event manually on the second control. However, this puts things in an infinite loop of recursion. I thought of a way to get around the recursion, but it reqires a global variable.
Is there a better way than this, preferably one that doesn't require a global variable?
ml_inEvent = false;
$ctlToVal.bind('keyup change', {feedbackCtl: ml_feedback, controlsToMonitor: ary, validationGroup: this.validationGroup, controlToFire: ctlToFire}, function(event) {
// Other processing happens here...
if (event.data.controlToFire != '') {
var $controlToFire = $('#' + event.data.controlToFire);
if ($controlToFire.length) {
// Use a global variable to ensure this event is not fired again
// as a result of calling the other one
if (!ml_inEvent) {
ml_inEvent = true;
$controlToFire.change();
ml_inEvent = false;
}
}
}
});
You can use the extraParameters argument on .trigger() to break out, for example:
$ctlToVal.bind('keyup change', {feedbackCtl: ml_feedback, controlsToMonitor: ary, validationGroup: this.validationGroup, controlToFire: ctlToFire}, function(event, fire) {
// Other processing happens here...
if(fire !== false) $('#' + event.data.controlToFire).trigger('change', false);
});
You can give it a try here. What this does is the event handler callback not only receives the event object but also any other arguments you pass in, in this case we're just using a simple false and a !=== check this in important so undefined (the parameter not passed at all) still changes both controls. So for instance $("#control").change() would change both controls, but still not loop...you can test that here.

Resources