0

I have a function that expects click event object as parameter. For example:

toggle: function (e) {
//does all the required work and then calls cancelEvent

this.cancelEvent(e);//IMPORTANT TO HANDLE LOCAL ANCHORS
    },


cancelEvent:function(e) {
    if (!e) e = window.event;
        if (e.preventDefault) {
        e.preventDefault();
                  } else {
            e.returnValue = false;
                  }
    },

I need to call toggle function on the page load.

I tried calling it without passing event parameter. However, doing so breaks the expected functionality and everything becomes un-editable.

Is there anyway I can get the current event object and pass it to the function?

Or should I attach load event too the event listener?

Please let me know what is the way out?

2 Answers 2

1

No need to even use jQuery. JavaScript in the browser includes a native Event object. So you should be able to call your toggle function directly (assuming you have access to the scope it was defined in) like this...

var fakeEvent = new Event('click');
toggle(fakeEvent);

Be sure to test thoroughly. If your code is relying on certain property values that the event would only have if it were triggered from a real user click then this may not work for you.

A better option would be to refactor so that the functionality that is shared by both page load and click is factored into a new function which can be called from both the click event handler function and the page load logic.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes you can create an event using jQuery:

var e = $.Event('click');
$element.trigger(e); // Triggers click event on element

Here's documentation on $.Event. Triggering a click event using jQuery the following way would also create an event object for you:

$element.click();

Comments

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.