testing123
testing123

Reputation: 831

javascript indexOf check in if statement

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.

Upvotes: 2

Views: 22768

Answers (3)

Ben Wrighton
Ben Wrighton

Reputation: 371

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

Upvotes: 2

silly
silly

Reputation: 7887

try this

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

Upvotes: 6

T.J. Crowder
T.J. Crowder

Reputation: 1074108

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) {

Upvotes: 3

Related Questions