rwehresmann rwehresmann - 18 days ago 6
Javascript Question

Call JQuery function each time the page is shown

I have a simple question. Here is my situation:

Each time that I show an especific page, I call this JQuery function:

<script text="text/>JavaScript">
$(window).on('load', function(){
$('body').addClass('background-image')
});
</script>


That set a background image in my page. It work fine when I load/refresh the page, but if I redirect to this page by a link, the JQuery function is not called. For instance: I load the home page, the image is set; I click in a link to visit the login page, and I click in a link again who redirect me to home page, but the image is not set.

How can I do to call my JQuery function every time the page is shown?

Answer

Put the event binding code inside jQuery ready() function. It will ensure that your event will be bound only after loading of jQuery -

    <script text="text/>JavaScript">
         $(document).ready(function() { 
             $(window).on('load', function(){
                $('body').addClass('background-image')
            });
        });
   </script>
Comments