How to bind three events to the same function in Jquery or jJavascript?

112 views Asked by At

Can anyone explain how can three events can be bind to same function ? i.e. same function should be called when the following events happen.

  • window unload.
  • on pressing 'ESC' button.
  • on clicking 'close' class.

I have written function on clicking '.close' class in following way:

<script>
$(document).ready(function() {
    var start = new Date().getTime();
    var starttime = new Date(start);
    $(".close").click(function () {
        jwplayer('mediaplayer').stop();
        end = new Date().getTime();
        endtime = new Date(end);            
        $.ajax({ 
          url: "/courses/136",
          data: {'timeSpent': endtime - starttime},
        });
    });

  });
</script>

The same thing should happen for window.unload() and on pressing ESC button. Is there any Jquery method for this.

3

There are 3 answers

1
jsam On

Create a function that is responsible for handling the events and then you just have to pass that function to every event you want to execute it.

<script>
  $(document).ready(function() {
    var start = new Date().getTime();
    var starttime = new Date(start);

    var eventHandler = function (event) {
        jwplayer('mediaplayer').stop();
        end = new Date().getTime();
        endtime = new Date(end);            
        $.ajax({ 
          url: "/courses/136",
          data: {'timeSpent': endtime - starttime},
        });
    };

    $(".close").click(eventHandler);
    $(window).on("unload", eventHandler);
    $(document).on("keydown", function(e) {
        if (e.which == 27) {
            eventHandler(e);
        }
    });
  });
</script>
1
T.J. Crowder On

You just define the function:

function handler() {
    jwplayer('mediaplayer').stop();
    end = new Date().getTime();
    endtime = new Date(end);            
    $.ajax({ 
      url: "/courses/136",
      data: {'timeSpent': endtime - starttime},
    });
}

...and bind it three times; for the ESC key part you probably want a wrapper:

$(".close").click(handler);
$(window).on("unload", handler);
$(document).on("keydown", function(e) { // Or whatever element is relevant
    if (e.which == 27) {
        handler.call(this, e);          // With the above, just `handler();` would work too
    }
});
0
nnnnnn On

The functions that you pass to jQuery methods like .click() don't have to be anonymous. You can refer to a function by name. So:

function yourFunction() {
   // do your jwplayer and ajax thing here
}

$(window).on("unload", yourFunction);
$(".close").click(yourFunction);
$(document).on("keyup", function(e) {
  if (e.which == 27)
    yourFunction();
});