Javacript onmouseevent counter


(Pee) #1

Hello,
Im looking for javascript that will count the number of times (e.g.: 3 times) onmouseup occurs in a scene, (and then after a certain number of clicks, jumps to the next scene).
I imagine this sisnt too hard to do but cant find example javascript anywhere (Im not a regular user of Javascript)

Thanks,
adi


#3

@Adi

Demo Project: mouseUpCounter_JHSv1.hype.zip (32.3 KB)

Demo here.

Key JavaScript Concept : addEventListener.

Description:
When the initial Scene opens the “On Scene Load” handler (in the “Scene Inspector”) triggers the “mouseUpCounter” function. This function is designed to go to the next scene on the 4th “mouseUp”. This function registers “mouseUp” events anywhere in the Scene using the addEventListener method. There is a text field with an ID of “ClickCounter” that displays the number of “mouseUp” events. This text field serves as a visual aid in the Demo - it is not a necessary part of the code.


(Pee) #4

Thanks Jim! This is great! :slight_smile:
Will use in the project today, its nice simple code and easy for people to use.

Cheers!
x Adi


(Pee) #5

Is it possible to have this mouse track function triggered only by the buttons on the screen (in no particular order)?
Without manually assigning x and y places on the screen (which would be a total pain).
Could I select all buttons and give them an element ID perhaps?
Am i on the right track?

x
Adi


#6

@Adi

Good - but You do not need to give the buttons or other elements You wish to track an ID:
Project demo: mouseUpCounter_JHSv2.hype.zip (31.2 KB)

We can skip the “addEventListener” entirely since we know it will just be a select group of buttons we are tracking.

We still utilize the global variable “counter” but in addition to its use in the JavaScript function (more on that in a short bit) we also place it in the “Head HTML” of the main document (“Document Inspector” > “Edit Head HTML”) where we give “counter” an initial value of “0”.

<script>
counter = 0;
</script>


The buttons You wish to have count towards a click will have their “On MouseUp” handler set to the “mouseUpCounter” function. Again, You do not need IDs for this set-up. You can group the buttons together to make it easy to assign event handler(s) making sure that You select the actual elements - not the group’s enclosing folder (i.e. “Click Count”). Simply select all the elements at once and assign the handler and the JavaScript function in one blow - as shown in the screen capture just below.


**"mouseUpCounter" function:** As in the example in my previous post the _"getElementById("ClickCounter).innerHTML"_ code is intended as a visual aid only - it is not required to make the code function.
    counter += 1;
    hypeDocument.getElementById('ClickCounter').innerHTML = counter;
	if(counter > 3) {
	   hypeDocument.showNextScene(hypeDocument.kSceneTransitionCrossfade, 1.1);
	   counter = 0;
	}