2

I know that there is a lot of questions like mine, but I don't think it's a duplicate.

I want to create my own custom event, for exemple onresize or onshake.

And I would like to make a library, then the user of my library would just write that :

<script src="theLib.js" ></script>
<script>
window.addEventListener("shake",myFunc,false);
</script>

I saw a lot of tutoriels and questions on stackoverflow but either they are using jQuery(I want the most simple exemple to make a custom event) or the user must not just write window.addEventListener.

Can you please explain me the most basic way to add a custom event?

7

2 Answers 2

2

I found the answer finally :

//Library part
var evt=document.createEvent("Event");
evt.initEvent("foo",true,true);
function blah()
{
    window.dispatchEvent(evt);
}
window.addEventListener("load",blah,false);

//User part
window.addEventListener("foo",function(){alert("Hi");},false);
Sign up to request clarification or add additional context in comments.

Comments

1

You'll want to trigger the event somehow. This answer gives particularly good depth: How to trigger event in JavaScript?

You'll probably have to use document instead of window, though.

4 Comments

From what I understand, by sing the initEvent method you create an event which can be fired on any element--the document, the window, a text field, whatever. So you simply use addEventListener on any object which gets that event fired.
And where do I write the tests (for exemple, testing if the iphone is shaked or not)
Anywhere in the document. Doesn't matter where. The trouble is figuring out when the phone is shaken, but it seems like you've taken care of that.
then, I write function dataavailable(){/*Tests*/} then the code of stackoverflow.com/questions/2490825/…, then window.addEventListener("dataavailable",otherFunc,false); ???????

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.