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?

user1365010
  • 3,185
  • 8
  • 24
  • 43

2 Answers2

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);
user1365010
  • 3,185
  • 8
  • 24
  • 43
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.

Community
  • 1
  • 1
Will
  • 1,621
  • 15
  • 20
  • 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. – Will Jun 07 '12 at 19:54
  • And where do I write the tests (for exemple, testing if the iphone is shaked or not) – user1365010 Jun 07 '12 at 19:57
  • 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. – Will Jun 07 '12 at 19:58
  • then, I write `function dataavailable(){/*Tests*/}` then the code of http://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript, then `window.addEventListener("dataavailable",otherFunc,false);` ??????? – user1365010 Jun 07 '12 at 20:01