Rahul
Rahul

Reputation: 518

Prevent page reload jQuery from only one page of a website

I am using this jQuery on a website

jQuery(document).ready(function($) {
    var windowWidth = jQuery(window).width();
    jQuery(window).resize(function(){
        if (jQuery(window).width() != windowWidth) {
              windowWidth = jQuery(window).width();
              location.reload();
        }
    });
});

The purpose is to reload a page when the screen size changes. For example a user is viewing it in portrait mode on a phone then switches to the landscape mode.

But I have one page in the website that I don't want to reload when the screen is resized.

Upvotes: 0

Views: 65

Answers (2)

Bharatsing Parmar
Bharatsing Parmar

Reputation: 2455

Try this:

This will not reload for particular page. For all other pages its reload

function getPageName(url) {
    var index = url.lastIndexOf("/") + 1;
    var filenameWithExtension = url.substr(index);
    var filename = filenameWithExtension.split(".")[0]; // <-- added this line
    return filename;                                    // <-- added this line
}

jQuery(document).ready(function($) {
    var url = window.location.href;
    var pagename=getPageName(url);

    if(pagename!="pagenotreload.html"){
      var windowWidth = jQuery(window).width();
      jQuery(window).resize(function(){
        if (jQuery(window).width() != windowWidth) {
              windowWidth = jQuery(window).width();
                            location.reload();
        }
      });
    }
});

Upvotes: 0

There are many ways to do this, the most simplest in my view is that you can define a boolean variable on the window object such as window.preventReload that isn't set to true unless in that specific window, and in your jQuery code check it before reloading, like this:

jQuery(document).ready(function($) {
    var windowWidth = jQuery(window).width();
    jQuery(window).resize(function(){
        if (window.preventReload !== true && jQuery(window).width() != windowWidth) {
              windowWidth = jQuery(window).width();
              location.reload();
        }
    });
});

Upvotes: 1

Related Questions