how to write a code to run same function on load and on ajax call2019 Community Moderator ElectionHow can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?How to manage a redirect request after a jQuery Ajax calljQuery multiple events to trigger the same functionjQuery: Return data after ajax call successDetect changed input text boxHow to make an AJAX call without jQuery?Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for itHow do I return the response from an asynchronous call?Function to determine if DOM and Images are loaded within AJAX call .loadUsing async/await with a forEach loop

Is it true that real estate prices mainly go up?

Placing subfig vertically

Is Gradient Descent central to every optimizer?

Why is this plane circling around the Lucknow airport every day?

Does "variables should live in the smallest scope as possible" include the case "variables should not exist if possible"?

Do Bugbears' arms literally get longer when it's their turn?

Could you please stop shuffling the deck and play already?

Reverse string, can I make it faster?

Look through the portal of every day

How do I locate a classical quotation?

Why does Captain Marvel assume the people on this planet know this?

Why would one plane in this picture not have gear down yet?

How strictly should I take "Candidates must be local"?

In the late 1940’s to early 1950’s what technology was available that could melt a LOT of ice?

PTIJ: How can I halachically kill a vampire?

Why don't MCU characters ever seem to have language issues?

Rejected in 4th interview round citing insufficient years of experience

How to clip a background including nodes according to an arbitrary shape?

Single word request: Harming the benefactor

PTIJ: Why can't I eat anything?

Do I really need to have a scientific explanation for my premise?

How do I deal with a powergamer in a game full of beginners in a school club?

Unreachable code, but reachable with exception

How could our ancestors have domesticated a solitary predator?



how to write a code to run same function on load and on ajax call



2019 Community Moderator ElectionHow can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?How to manage a redirect request after a jQuery Ajax calljQuery multiple events to trigger the same functionjQuery: Return data after ajax call successDetect changed input text boxHow to make an AJAX call without jQuery?Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for itHow do I return the response from an asynchronous call?Function to determine if DOM and Images are loaded within AJAX call .loadUsing async/await with a forEach loop










-1















The code is very simple, it changes a text on a blog but this blog has pagination that brings content through ajax.



So the code is changing the text on load and on ajax new content.



$(document).ready(function() 
$('.author').each(function()
$(this).text('Jim')
);

$(document).ajaxStop(function()
$('.author').each(function()
$(this).text('Jim')
);
);
);


The question I'm asking is can I write a better code. This doesn't look right to me because I'm executing the same code twice.



Is there a better way?



Thanks for help.










share|improve this question







New contributor




babarosa8 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Create a function.

    – Rory McCrossan
    Mar 6 at 16:25















-1















The code is very simple, it changes a text on a blog but this blog has pagination that brings content through ajax.



So the code is changing the text on load and on ajax new content.



$(document).ready(function() 
$('.author').each(function()
$(this).text('Jim')
);

$(document).ajaxStop(function()
$('.author').each(function()
$(this).text('Jim')
);
);
);


The question I'm asking is can I write a better code. This doesn't look right to me because I'm executing the same code twice.



Is there a better way?



Thanks for help.










share|improve this question







New contributor




babarosa8 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















  • Create a function.

    – Rory McCrossan
    Mar 6 at 16:25













-1












-1








-1








The code is very simple, it changes a text on a blog but this blog has pagination that brings content through ajax.



So the code is changing the text on load and on ajax new content.



$(document).ready(function() 
$('.author').each(function()
$(this).text('Jim')
);

$(document).ajaxStop(function()
$('.author').each(function()
$(this).text('Jim')
);
);
);


The question I'm asking is can I write a better code. This doesn't look right to me because I'm executing the same code twice.



Is there a better way?



Thanks for help.










share|improve this question







New contributor




babarosa8 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












The code is very simple, it changes a text on a blog but this blog has pagination that brings content through ajax.



So the code is changing the text on load and on ajax new content.



$(document).ready(function() 
$('.author').each(function()
$(this).text('Jim')
);

$(document).ajaxStop(function()
$('.author').each(function()
$(this).text('Jim')
);
);
);


The question I'm asking is can I write a better code. This doesn't look right to me because I'm executing the same code twice.



Is there a better way?



Thanks for help.







javascript jquery ajax






share|improve this question







New contributor




babarosa8 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




babarosa8 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




babarosa8 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Mar 6 at 16:14









babarosa8babarosa8

31




31




New contributor




babarosa8 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





babarosa8 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






babarosa8 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












  • Create a function.

    – Rory McCrossan
    Mar 6 at 16:25

















  • Create a function.

    – Rory McCrossan
    Mar 6 at 16:25
















Create a function.

– Rory McCrossan
Mar 6 at 16:25





Create a function.

– Rory McCrossan
Mar 6 at 16:25












4 Answers
4






active

oldest

votes


















0














An alternative to wrapping the code in a function is to attach multiple event listeners to the document with the same callback, for example:



$( document ).on( 'ready ajaxStop', function() 
$( '.author' ).each( function()
$( this ).text( 'Jim' );
);
);


This code should run on both the ready and ajaxStop events.



Edit



From a quick look at the documentation this is no longer supported...




There is also $(document).on( "ready", handler ), deprecated as of jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.




A "hacky" fix to this would be to do something like:



$( document ).on( 'ready ajaxStop', function() 
$( '.author' ).each( function()
$( this ).text( 'Jim' );
);
).trigger( 'ready' );


Working example: https://jsfiddle.net/j6dwu4zL/






share|improve this answer
































    2














    You could put the changing of author into a function and call that where needed.



    $(document).ready(function() 
    changeAuthor('Jim');

    $(document).ajaxStop(function()
    changeAuthor('Jim');
    );
    );

    function changeAuthor(name)
    $('.author').text(name)






    share|improve this answer






























      0














      Wrap code with some function



      $(document).ready(function() 
      Jim()
      $(document).ajaxStop(function()
      Jim()
      );
      );

      function Jim()
      $('.author').each(function()
      $(this).text('Jim')
      );






      share|improve this answer






























        0














        You could write a separate function so the code is only done twice. It also might be better to call that function in the success method of the Ajax call so you can control for errors, instead of setting it to whatever comes back.



        $(document).ready(function() 
        Author();
        );

        $.ajax(
        //params
        success: function()
        Author();

        error: function(response.responsetext)
        console.log(response.responsetext);

        );

        function Author()
        $('.author').each(function()
        $(this).text('Jim');
        );






        share|improve this answer






















          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );






          babarosa8 is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55027600%2fhow-to-write-a-code-to-run-same-function-on-load-and-on-ajax-call%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          An alternative to wrapping the code in a function is to attach multiple event listeners to the document with the same callback, for example:



          $( document ).on( 'ready ajaxStop', function() 
          $( '.author' ).each( function()
          $( this ).text( 'Jim' );
          );
          );


          This code should run on both the ready and ajaxStop events.



          Edit



          From a quick look at the documentation this is no longer supported...




          There is also $(document).on( "ready", handler ), deprecated as of jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.




          A "hacky" fix to this would be to do something like:



          $( document ).on( 'ready ajaxStop', function() 
          $( '.author' ).each( function()
          $( this ).text( 'Jim' );
          );
          ).trigger( 'ready' );


          Working example: https://jsfiddle.net/j6dwu4zL/






          share|improve this answer





























            0














            An alternative to wrapping the code in a function is to attach multiple event listeners to the document with the same callback, for example:



            $( document ).on( 'ready ajaxStop', function() 
            $( '.author' ).each( function()
            $( this ).text( 'Jim' );
            );
            );


            This code should run on both the ready and ajaxStop events.



            Edit



            From a quick look at the documentation this is no longer supported...




            There is also $(document).on( "ready", handler ), deprecated as of jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.




            A "hacky" fix to this would be to do something like:



            $( document ).on( 'ready ajaxStop', function() 
            $( '.author' ).each( function()
            $( this ).text( 'Jim' );
            );
            ).trigger( 'ready' );


            Working example: https://jsfiddle.net/j6dwu4zL/






            share|improve this answer



























              0












              0








              0







              An alternative to wrapping the code in a function is to attach multiple event listeners to the document with the same callback, for example:



              $( document ).on( 'ready ajaxStop', function() 
              $( '.author' ).each( function()
              $( this ).text( 'Jim' );
              );
              );


              This code should run on both the ready and ajaxStop events.



              Edit



              From a quick look at the documentation this is no longer supported...




              There is also $(document).on( "ready", handler ), deprecated as of jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.




              A "hacky" fix to this would be to do something like:



              $( document ).on( 'ready ajaxStop', function() 
              $( '.author' ).each( function()
              $( this ).text( 'Jim' );
              );
              ).trigger( 'ready' );


              Working example: https://jsfiddle.net/j6dwu4zL/






              share|improve this answer















              An alternative to wrapping the code in a function is to attach multiple event listeners to the document with the same callback, for example:



              $( document ).on( 'ready ajaxStop', function() 
              $( '.author' ).each( function()
              $( this ).text( 'Jim' );
              );
              );


              This code should run on both the ready and ajaxStop events.



              Edit



              From a quick look at the documentation this is no longer supported...




              There is also $(document).on( "ready", handler ), deprecated as of jQuery 1.8 and removed in jQuery 3.0. Note that if the DOM becomes ready before this event is attached, the handler will not be executed.




              A "hacky" fix to this would be to do something like:



              $( document ).on( 'ready ajaxStop', function() 
              $( '.author' ).each( function()
              $( this ).text( 'Jim' );
              );
              ).trigger( 'ready' );


              Working example: https://jsfiddle.net/j6dwu4zL/







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 6 at 16:38

























              answered Mar 6 at 16:29









              Levi ColeLevi Cole

              430419




              430419























                  2














                  You could put the changing of author into a function and call that where needed.



                  $(document).ready(function() 
                  changeAuthor('Jim');

                  $(document).ajaxStop(function()
                  changeAuthor('Jim');
                  );
                  );

                  function changeAuthor(name)
                  $('.author').text(name)






                  share|improve this answer



























                    2














                    You could put the changing of author into a function and call that where needed.



                    $(document).ready(function() 
                    changeAuthor('Jim');

                    $(document).ajaxStop(function()
                    changeAuthor('Jim');
                    );
                    );

                    function changeAuthor(name)
                    $('.author').text(name)






                    share|improve this answer

























                      2












                      2








                      2







                      You could put the changing of author into a function and call that where needed.



                      $(document).ready(function() 
                      changeAuthor('Jim');

                      $(document).ajaxStop(function()
                      changeAuthor('Jim');
                      );
                      );

                      function changeAuthor(name)
                      $('.author').text(name)






                      share|improve this answer













                      You could put the changing of author into a function and call that where needed.



                      $(document).ready(function() 
                      changeAuthor('Jim');

                      $(document).ajaxStop(function()
                      changeAuthor('Jim');
                      );
                      );

                      function changeAuthor(name)
                      $('.author').text(name)







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Mar 6 at 16:17









                      Jordan MaduroJordan Maduro

                      513210




                      513210





















                          0














                          Wrap code with some function



                          $(document).ready(function() 
                          Jim()
                          $(document).ajaxStop(function()
                          Jim()
                          );
                          );

                          function Jim()
                          $('.author').each(function()
                          $(this).text('Jim')
                          );






                          share|improve this answer



























                            0














                            Wrap code with some function



                            $(document).ready(function() 
                            Jim()
                            $(document).ajaxStop(function()
                            Jim()
                            );
                            );

                            function Jim()
                            $('.author').each(function()
                            $(this).text('Jim')
                            );






                            share|improve this answer

























                              0












                              0








                              0







                              Wrap code with some function



                              $(document).ready(function() 
                              Jim()
                              $(document).ajaxStop(function()
                              Jim()
                              );
                              );

                              function Jim()
                              $('.author').each(function()
                              $(this).text('Jim')
                              );






                              share|improve this answer













                              Wrap code with some function



                              $(document).ready(function() 
                              Jim()
                              $(document).ajaxStop(function()
                              Jim()
                              );
                              );

                              function Jim()
                              $('.author').each(function()
                              $(this).text('Jim')
                              );







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Mar 6 at 16:18









                              prasanthprasanth

                              14.1k21336




                              14.1k21336





















                                  0














                                  You could write a separate function so the code is only done twice. It also might be better to call that function in the success method of the Ajax call so you can control for errors, instead of setting it to whatever comes back.



                                  $(document).ready(function() 
                                  Author();
                                  );

                                  $.ajax(
                                  //params
                                  success: function()
                                  Author();

                                  error: function(response.responsetext)
                                  console.log(response.responsetext);

                                  );

                                  function Author()
                                  $('.author').each(function()
                                  $(this).text('Jim');
                                  );






                                  share|improve this answer



























                                    0














                                    You could write a separate function so the code is only done twice. It also might be better to call that function in the success method of the Ajax call so you can control for errors, instead of setting it to whatever comes back.



                                    $(document).ready(function() 
                                    Author();
                                    );

                                    $.ajax(
                                    //params
                                    success: function()
                                    Author();

                                    error: function(response.responsetext)
                                    console.log(response.responsetext);

                                    );

                                    function Author()
                                    $('.author').each(function()
                                    $(this).text('Jim');
                                    );






                                    share|improve this answer

























                                      0












                                      0








                                      0







                                      You could write a separate function so the code is only done twice. It also might be better to call that function in the success method of the Ajax call so you can control for errors, instead of setting it to whatever comes back.



                                      $(document).ready(function() 
                                      Author();
                                      );

                                      $.ajax(
                                      //params
                                      success: function()
                                      Author();

                                      error: function(response.responsetext)
                                      console.log(response.responsetext);

                                      );

                                      function Author()
                                      $('.author').each(function()
                                      $(this).text('Jim');
                                      );






                                      share|improve this answer













                                      You could write a separate function so the code is only done twice. It also might be better to call that function in the success method of the Ajax call so you can control for errors, instead of setting it to whatever comes back.



                                      $(document).ready(function() 
                                      Author();
                                      );

                                      $.ajax(
                                      //params
                                      success: function()
                                      Author();

                                      error: function(response.responsetext)
                                      console.log(response.responsetext);

                                      );

                                      function Author()
                                      $('.author').each(function()
                                      $(this).text('Jim');
                                      );







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Mar 6 at 16:20









                                      torogadudetorogadude

                                      350110




                                      350110




















                                          babarosa8 is a new contributor. Be nice, and check out our Code of Conduct.









                                          draft saved

                                          draft discarded


















                                          babarosa8 is a new contributor. Be nice, and check out our Code of Conduct.












                                          babarosa8 is a new contributor. Be nice, and check out our Code of Conduct.











                                          babarosa8 is a new contributor. Be nice, and check out our Code of Conduct.














                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55027600%2fhow-to-write-a-code-to-run-same-function-on-load-and-on-ajax-call%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

                                          Алба-Юлія

                                          Захаров Федір Захарович