0

I am trying to run a javascript only on mobile phone using Foundation and Rails, (and haml, this is haml example, but don't pay attention to that).

I am doing something like this:

.row
 =# something for large screens
    .row.show-for-small-only
      .small-10.small-centered.columns
        = javascript_tag "$('.someClassIPointTo').myfunction();"

So I am trying to run this javascript only for small size screens, and NOT for large screens. Is there a way for doing that other then duplicating the code?

j0k
  • 21,914
  • 28
  • 75
  • 84
Aleks
  • 4,135
  • 2
  • 31
  • 59

2 Answers2

0

You can use simple javascript to detect whether the device is mobile or not and then, run the code you want.

if( (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) &&
    (window.innerWidth < SCREEN_WIDTH) && (window.innerHeight < SCREEN_HEIGHT) ) {
 // some code..
}

Source: What is the best way to detect a mobile device in jQuery?

Community
  • 1
  • 1
Zero Fiber
  • 4,089
  • 1
  • 20
  • 33
  • Well that depends on the mobile devices. I am more concentrated to check for small sized screens. But I might have some answer, hm, I will try it and I will post an answer – Aleks Jan 29 '14 at 13:23
  • You can also check the size of screen and add a condition to the if statement. – Zero Fiber Jan 29 '14 at 13:24
  • I am using foundation. Is there something that I can use that already exists there? `.show-for-small-only` or something like that? – Aleks Jan 29 '14 at 13:28
  • I dont know about Foundation, but I added in the condition of small screen size. – Zero Fiber Jan 29 '14 at 13:30
  • Thanks, but I don't like to check based on type of the device, also I cant check for screen width as it can be different – Aleks Jan 29 '14 at 13:50
0

I have found an answer to my own question, and here it goes:

I have added a class .my_indicator_class inside .show-for-small class. Something like this (haml example):

.show_for_small
 .my_indicator_class

And then in my javascript code I have used it to check whether this element is visible, like this:

var isVisible = $('.my_indicator_class').is(":visible");

if(isVisible){
  //My code that will run only for small screens
}else{
  // Code for big screens :)
}

And whola, that's it.

Aleks
  • 4,135
  • 2
  • 31
  • 59