最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Execute jQuery function after page refresh - Stack Overflow

programmeradmin2浏览0评论

I did a function where I checked if the window has been resized and an element is visible in order to change some classes and add a little bit of css .The problem is if I refresh the page the changes are reverted . Here is a snippet of my code :

$(document).ready(function() {

 $(window).resize(function() {
   if(isMenuVisible() == true){
     $('#my-nav').removeClass('navbar-fixed-bottom');
     $('#my-nav').addClass('navbar-fixed-top');
     $('body').css('padding-top', '50px');
      } else{
      $('#my-nav').removeClass('navbar-fixed-top');
      $('#my-nav').addClass('navbar-fixed-bottom');
      $('body').css('padding-top', '0');  
   }
 }) ;
});

I did a function where I checked if the window has been resized and an element is visible in order to change some classes and add a little bit of css .The problem is if I refresh the page the changes are reverted . Here is a snippet of my code :

$(document).ready(function() {

 $(window).resize(function() {
   if(isMenuVisible() == true){
     $('#my-nav').removeClass('navbar-fixed-bottom');
     $('#my-nav').addClass('navbar-fixed-top');
     $('body').css('padding-top', '50px');
      } else{
      $('#my-nav').removeClass('navbar-fixed-top');
      $('#my-nav').addClass('navbar-fixed-bottom');
      $('body').css('padding-top', '0');  
   }
 }) ;
});
Share Improve this question asked Aug 7, 2016 at 19:01 Adrian.IAdrian.I 1801 gold badge2 silver badges10 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

$(document).ready(function() {  
  
 function resizeChanges(){
    if(isMenuVisible() == true){
       $('#my-nav').removeClass('navbar-fixed-bottom');
       $('#my-nav').addClass('navbar-fixed-top');
       $('body').css('padding-top', '50px');
     }else{
       $('#my-nav').removeClass('navbar-fixed-top');
       $('#my-nav').addClass('navbar-fixed-bottom');
       $('body').css('padding-top', '0');  
     }   
 }
 
 $(window).resize(resizeChanges);
 
 resizeChanges();
});

This way you define a separate function to make your changes, you add the event listener to trigger it but also you call that function itself after the load/refresh.

Try trigger the resize event on window after load.

$(window).trigger('resize');

If the user refreshes the page, all changes in the client side will be lost. However, you can detect when the user refreshes the page and save the values in the server side. And then, when the page is loaded again, restore those values.

$(window).on('beforeunload', function(){
    // save the values to server side
});

$(window).on('load', function(){
    // restore values
});
发布评论

评论列表(0)

  1. 暂无评论