Search code examples
jquerydocument-ready

document.ready not working on linking a page through ahref


The document only loads when the page is hit directly with its url, it does not work if the page is loaded through an ahref link.

$(document).ready(function(){ 
alert( "document loaded" );
});

I know this has been asked before and I tried a few things and nothing worked. The window also does not get loaded on opening a page through a link

$( window ).on( "load", function() {
  alert( "window loaded" );
});

I also tried pageinit, not sure if I used it wrong but it did not work. Any help will be appreciated

Also, I am using rails

My application

<html>
  <head>
    <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
    <title>DevPortal</title>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

I link my one page to another using the following code snippet:

<p>
  <a class="btn btn-secondary" href="new_page">
    My link
 </a>
</p>

Solution

  • This worked for me as I was using turbolinks

    $(document).on('turbolinks:load', function() {
       alert("It works");
    });