public static
public static

Reputation: 12990

How to convert this eventlistener to jQuery

How can I refactor the below snippet to using jQuery.

  window.onload = function () {
        if (window.addEventListener) {
            window.addEventListener("message", doSomething, false);
        }
        else {
            if (window.attachEvent) {
                window.attachEvent("onmessage", doSomething);
            }
        }
    }

Upvotes: 0

Views: 133

Answers (2)

jfriend00
jfriend00

Reputation: 707238

In jQuery, you can simply do this:

$(window).on("message", doSomething);

This attaches an event handler for the "message" event to the window object.


FYI, there's no need to wait for window.onload just to attach an event handler to the window object as it already exists so there's no need to wait.

If you did need to wait for some other reason, you could put it inside of:

// wait for all document resources to load
$(window).load(function() {
    // code here
});

or

// wait for DOM to be loaded
$(document).ready(function() {
    // code here
});

depending upon what you needed to wait for.

Upvotes: 2

Morklympious
Morklympious

Reputation: 1095

If 'onmessage' and 'message' are events specific to the window object, You can wrap the window in a jQuery wrapper $(window)

And then you can use jQuery's event system to bind those events with .on()

So it'd look something like this:

$(window).on('message', function(){ // do something });
$(window).on('onmessage', function(){ // do something });

You can read more about .on() at the jQuery API

Some people will tell you to use bind, but from the docs:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements.

So, depending on your jQuery version, you'll either use on() or bind() accordingly.

Hope that helps!

Upvotes: 1

Related Questions