0

Hi guys I can't seem to find the exact thing I am trying to do, and being a javascript amateur I can't seem to wrangle it. Basically... I have this script attached to various elements on my page

$(document).ready(function() {
$("h1, h2, h5, .class1, .class2 #image1").click(function () {
    window.open('https://www.linkdesktop.com');
});

});

and what I want to do is: IF on mobile device THEN switch www.linkdesktop.com TO www.linkmobile.com

Is this possible, do I do it based on screen size or using some sort of mobile detect script?

Answers appreciated, thanks a lot.


Ok so thanks for the answer

so perhaps somthing like this?

    var userAgent = window.navigator.userAgent;

$(document).ready(function() {
if( (Android|webOS|iPhone|iPad|iPod|BlackBerry).test(navigator.userAgent) ) {

$("h1, h2, h5, .class1, .class2 #image1").click(function () {
    window.open('https://www.linkmobile.com');
});

}
else {

$("h1, h2, h5, .class1, .class2 #image1").click(function () {
    window.open('https://www.linkdesktop.com');
});

}

});
James
  • 11
  • 6

2 Answers2

1

In my last project I've used this solution to check mobile user. Elegant and simply.

var isMobile = {
  Android: function() {
    return navigator.userAgent.match(/Android/i);
  },
  BlackBerry: function() {
    return navigator.userAgent.match(/BlackBerry/i);
  },
  iOS: function() {
    return navigator.userAgent.match(/iPhone|iPad|iPod/i);
  },
  Opera: function() {
    return navigator.userAgent.match(/Opera Mini/i);
  },
  Windows: function() {
    return navigator.userAgent.match(/IEMobile/i);
  },
  any: function() {
    return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
  }
};

if( isMobile.any() ) alert('Mobile');
Romain
  • 5,913
  • 3
  • 30
  • 38
Nico Vignola
  • 479
  • 8
  • 16
  • Ok thanks so if I use your method with variables declared above this is should work: ' $(document).ready(function() { if( isMobile.any() ) { $("h1, h2, h5, .class1, .class2 #image1").click(function () { window.open('https://www.linkmobile.com'); }); } else { $("h1, h2, h5, .class1, .class2 #image1").click(function () { window.open('https://www.linkdesktop.com'); }); } }); ' – James May 10 '13 at 13:43
  • Yes it will. But instead to declare the isMobile var globally, i would put isMobile inizialization and declaration inside $(document).ready(function(){ var isMobile = {...}; ); – Nico Vignola May 10 '13 at 13:50
0

You could check the user agent (window.navigator.userAgent), see Determine if user navigated from mobile Safari

Community
  • 1
  • 1
mguimard
  • 1,831
  • 12
  • 14