javascript indexOf check in if statement

16,588

Solution 1

try this

if(document.referrer.indexOf('/mobile') > -1 && screen.width < 700) {
}

Solution 2

You don't want document.write here (or virtually anywhere):

if(window.location.href.indexOf(document.referrer) > -1 &&
    screen.width <= 699) {

But your code and your question don't quite match, you've said

...if the referring url is coming from the /mobile directory...

That would be something more like

if(document.referrer.indexOf("/mobile") > -1 &&
    screen.width <= 699) {

Solution 3

Specifically addressing the indexOf check, 'does not equal' will also work and IMHO makes the intent a bit clearer.

if ( a.indexOf(somestring) !== -1 ) {

Applied to an example above

if(document.referrer.indexOf('/mobile') !== -1
Share:
16,588
testing123
Author by

testing123

Updated on June 05, 2022

Comments

  • testing123
    testing123 almost 2 years

    Having some difficulty getting this code to work. Essentially, I want to check if the referring url is coming from the /mobile directory and if not and the screen is a mobile device I want to redirect to the mobile site.

    <script type="text/javascript">
    if(window.location.href.indexOf("document.write(document.referrer)") > -1 &&
        screen.width <= 699) {
        document.location = "/mobile/mobile_home.asp";
    }
    
    </script>
    

    The code is currently placed in the head of the main home.asp.