2

I've fairly new to javascript and jQuery so help would be greatly appreciated.

I've designed a site from mobile up and used a slider to display a my block of image for small screens (< 500px).

The provided jQuery function placed in the head works fine:

<script>
jQuery(function($) {
$('.slider').sss();
});
</script>

but works all the time.

I've found an example of javascript to write a script to the head based on the window width that works pretty well:

var script = document.createElement('script');
script.type="text/javascript";

if(window.matchMedia("(max-width:499px)").matches) {
  jQuery(function($) {$(".slider").sss();});
}

document.getElementsByTagName('head')[0].appendChild(script);

But this doesn't respond to a changing window size. Once the function is loaded, it remains loaded and needs a manual refresh to either load or not load the function.

There must be a way to do this dynamically without having to refresh the page manually.

Anil_M
  • 8,692
  • 2
  • 32
  • 59
  • Does changing window size really matter in this case? if you're building it for small devices only, you should only care about the max width of said small device, they won't be resizing any more than changing from portrait to landscape. – Kevin B May 16 '16 at 19:23
  • Instead of depending on resize, try using the solution provided here http://stackoverflow.com/questions/3514784/what-is-the-best-way-to-detect-a-mobile-device-in-jquery to detect the device and invoke methods based on that. – Vimalan Jaya Ganesh May 16 '16 at 19:40
  • Not to discredit [@Vimalan's](http://stackoverflow.com/users/4872454/vimalan-jaya-ganesh) solution, but I personally would not recommend it because of how different peoples resolutions are (not to mention desktop versions of say android like [RemixOS](http://www.jide.com/remixos). I think you should only target that vendor OS if you need to state something specific for that OS. Like an app for instance. Otherwise I find it unnecessary and bad practice but every developer has their own style. Good mention though! – Michael Schwartz May 16 '16 at 19:57
  • @KevinB the site is not just for small devices, I was starting small and expanding instead of the other way round. The change from portrait to landscape crosses the threshold of using or not using the script. – user6342150 May 17 '16 at 17:53
  • then your problem is rather complicated. You can't just... undo javascript, you have to unbind events, remove elements and replace old ones, etc. If your plugin doesn't support that out of the box, good luck. – Kevin B May 17 '16 at 17:57
  • An easier alternative (but less performant) would be to duplicate the content, one for mobile one for desktop, and simply show/hide them with media queries. – Kevin B May 17 '16 at 18:00

3 Answers3

0

You can run your code on the resize event, like this:

function getDeviceDimension() {
    return {
        width: $(window).width()
    };
}

function setSliderSss() {
    var dd = getDeviceDimension();
    if (dd.width < 500) {
        $('.slider').sss();
    }
}

$(window).on('load resize', function() {
    setSliderSss();
});
Yosvel Quintero Arguelles
  • 15,149
  • 4
  • 33
  • 35
0

Weave: http://kodeweave.sourceforge.net/editor/#3769a18794a75c3973ad798812bf0ad2

You can call your function using the .on event listener; with this you can add in .load and .resize and by using say .width inside an if else statement $(this).width() < 500 you can change the .html of whatever element you want for mobile and for desktop.

Here's a simple example!

$(window).on("load resize", function() {
  if ($(this).width() < 500) {
    $("[data-action=change]").html("Mobile")
  } else {
    $("[data-action=change]").html("Desktop")
  }
})
body {
  padding: 1em;
  text-align: center;
}
<link href="https://necolas.github.io/normalize.css/4.1.1/normalize.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1 data-action="change">
  Desktop
</h1>

My advise here is if you're just styling the page for this effect. Don't use JS, Instead use CSS Media Queries.

You can change HTML content with CSS using the content property however I would only recommend doing so if you're making something simple like an On/Off switch.

BTW: In JavaScript there's something called Conditional (ternary) Operator now I wouldn't use it for this particular purpose, but it's something to note. I made a video tutorial on it, in the past, but basically you have <condition> ? <true-value> : <false-value>. In some cases you may want to use a ternary operator over an if else statement. Here's an example of using a ternary operator for your problem. (I'm using Vanilla/Pure JS for this demo)

Hope this helps.

Community
  • 1
  • 1
Michael Schwartz
  • 6,962
  • 12
  • 69
  • 126
-1

Created a simple screen detection that uses setInterval()... just to be different.

$_currentScreenWidth = $(window).width();
var screenDetection = setInterval(function() {
    $_newScreenWidth = $(window).width();
    if ($_currentScreenWidth !== $_newScreenWidth) {
        switch (true) {
            case ($_newScreenWidth <= 320): /** do something(); */  break;
            case ($_newScreenWidth > 320 && $_newScreenWidth <= 480): /** do something(); */ break;
            case ($_newScreenWidth > 480 && $_newScreenWidth <= 768): /** do something(); */  break;
            case ($_newScreenWidth > 768 && $_newScreenWidth < 960): /** do something(); */  break;
            case ($_newScreenWidth >= 960): /** do something(); */  break;
            /** add more screen sizes, and/or adjust the aforementioned accordingly */
            default: /** do something(); */  break;
        }
    }
}, 200); // adjust this value to control the interval rate, in milliseconds; the lower the rate, the greater the responsiveness.

But the resize() event was built for this kind of use-case:

$_currentScreenWidth = $(window).width();
$(window).resize(function() {
    $_newScreenWidth = $(window).width();
    if ($_currentScreenWidth !== $_newScreenWidth) {
        switch (true) {
            case ($_newScreenWidth <= 320): console.log('<= 320'); break;
            case ($_newScreenWidth > 320 && $_newScreenWidth <= 480): console.log('> 320 <= 480'); break;
            case ($_newScreenWidth > 480 && $_newScreenWidth <= 768): console.log('> 480 <= 768');  break;
            case ($_newScreenWidth > 768 && $_newScreenWidth < 960): console.log('> 768 < 960');  break;
            case ($_newScreenWidth >= 960): console.log('>= 960');  break;
            /** add more screen sizes, and/or adjust the aforementioned accordingly */
            default: /** do something(); */  break;
        }
    }
});
mferly
  • 1,586
  • 1
  • 11
  • 18