Eyad Farra
Eyad Farra

Reputation: 4423

how to trigger original event with JQuery

So sorry for my bad English words.

Hello, I have some problem when firing custom event in JQuery. My problem is :

I tried to simulate the same thing using http://jsfiddle.net/ editor like this:

         $(document).ready(function(){
// this what the site do when press enter key on textarea , the submit form with ajax to publish a comment.
          $("textarea").bind("keydown",function(e){
            if(e.which == 13){
              alert("enter pressed");
            }
          });
    // this what i need to do, firing the same event when i click on my button which i added by my extension.
          $("button").click(function(){
            var e = $.Event("keydown");
            e.which = 13;
            $("textarea").trigger(e);
          });
        });

the code above is run without any problem but when apply this simulation in target website no action happening . i imagine if the site using keydown, keyup, or keypress events to publish comment, so i tried using all event types, but all my tries failed. What i can do to fire the same of original event such as actual pressing enter key to submit comment ?

Upvotes: 3

Views: 1698

Answers (2)

Scott Stevens
Scott Stevens

Reputation: 380

why not try separating your logic? This is not tested code so you might have to play with it, but this general style will work and accomplish what it seems you are trying to do.

function myFunction()
{

    alert("enter pressed");
}

 $(document).ready(function(){
// this what the site do when press enter key on textarea , the submit form with ajax to publish a comment.
          $("textarea").bind("keydown",function(e){
             if(eventArg.which == 13){
                    myFunction();

              }
          });


    // this what i need to do, firing the same event when i click on my button which i added by my extension.
 $("button").click(function(){
         myFunction();
   });
 });

Upvotes: 0

sdespont
sdespont

Reputation: 14025

You could just create a new function to submit your comment and call it when :

  • User press ENTER in the textarea
  • User click on the button

     $(document).ready(function(){
    
         function submitComment()
         {
             //Do what you want to submit the textarea text
             var comment = $("textarea").html();
         }
    
         $("textarea").bind("keydown",function(e){
            if(e.which == 13){
               submitComment();
            }
         });
    
         $("button").click(function(){
            submitComment();
         });
     });
    

Upvotes: 1

Related Questions