July 5, 2012

Cancel Redirect in Javascript?

Question by Elite Gamer

i added this to the head of my page:

<script type="text/javascript">

if (screen.width <= 800) {
    window.location = "http://m.domain.com";
}

</script>

i have a button on my mobile version called “Main Site”.
I want the button to go to my main site, but not redirect back to my mobile site. How do i do this?

also, i only want them to go there once. So, the next time they enter my website name, i want it to take them to mobile site

Answer by Starx

If you already have a button to go your main site. Just link the main site to that button. What you can do extra is, use an url parameter to check and force the main layout. Something like

<a href="http://www.domain.com?forcelayout=main">Main site</a>

Check for this parameter, when you want to force the main layout. Or else, the script currently using will automatically do what you want to do.


Use the following function to read the query string. [Source]

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)')
                    .exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/+/g, ' '));
}

Next you can use it in your logic, like this:

if (screen.width <= 800 && getParameterByName('forceLayout') != 'main') {
    window.location = "http://m.domain.com";
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!