Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call jQuery function on small devices only

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.

like image 202
user6342150 Avatar asked Jul 19 '26 03:07

user6342150


1 Answers

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.

like image 129
Michael Schwartz Avatar answered Jul 20 '26 17:07

Michael Schwartz