How to generate window.event programmatically using Javascript?

I am currently testing a javascript block where it handles the event raised by clicking on a specific element in the window. Below is the code reference:

function someFunction() 
{

    var evt = window.event ? window.event : event;

    if (evt == null) { return; }

    var nodeElement = evt.srcElement;

    if (nodeElement == null) { return; }
    .
    .
    .
}

      

My current approach is to try and create a custom event in my test file that will populate window.event so that I can at least try to validate nodeElement == null. But I am having difficulty with this (not from Javascript backgound). How can I create a custom event (in IE)? I am currently doing unit testing using JsTestDriver so no html file is used. I don't mind using jQuery or just a Javascript solution.

Thank.

+2


source to share


3 answers


I would definitely use jQuery (or some other framework). It will make your life easier. I'm sure every browser will have a different way to fire the event.

http://docs.jquery.com/Events



With jQuery, you just do something like

$(window).trigger("eventname")

      

+3


source


I have currently written a blog series about custom events in jQuery. You can use .trigger

and .bind

, and it's really powerful.



0


source


As alex pointed out in his comment, you can use jQuery to create events with

$("css selector here").jQueryEventFunction(functionToCall);

      

So, following your example, if you want to call someFunction

when the label is clicked, you can do:

$("#label-id").click(someFunction);

      

Now if you want to simulate a click,

$("#label-id").click();

      

And it will be done.

EDIT . For window event, you can use

$(window).click(someFunction);

      

This will bind any click made in the window to someFunction

. And if you call $(window).click();

it will show a simulation of the click event calling someFunction

.

0


source







All Articles