Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

General

Load JS Assets based on screen resolution

Solved by Marcin View solution

Started by Pedro M 3 years ago · 4 replies · 362 views
3 years ago

Hi.

How can I execute a js script depending on the screen size?

It would be something like this:

TWIG
{% block javascripts %}
<script>
var width = {# sample code #}
   {% if screen < 980 %}
      {# javascript code #}
   {% endif %}
</script>
{% endblock %}

I've tested with

JS
var w = window.innerWidth
if w < 980 {
   {# code #}
}

but no resuts.

I don't know if this can be done directly in the Twig templates. Anyone who can help?

3 years ago Solution

try:

JS
if ((window.innerWidth || document.documentElement.clientWidth) < 980){ do some stuff }
3 years ago

Hi @lisekbox.

With your solution not work:

TWIG
{% block javascripts %}
<script>
if ((window.innerWidth || document.documentElement.clientWidth) < 980) { 
  /* Script  */
  }
</script>
{% endblock %}

Viewing the html source the script code is still loading in devices upper 980px.

3 years ago

Hmmmm just made simple test...

JS
<script>
  if ((window.innerWidth || document.documentElement.clientWidth) < 980) {
   console.log('test') 
  }
</script> 

and script is executing only on devices below 980px... but of course whole script code inside will be still loading on upper resolutions on page load, but will not execute instructions... If U dont want to load your script > 980 save code U want to run in file, then using JS create element script in footer with link to your file

3 years ago

Hi @lisekbox.

Indeed the JavaScript code appears in the source code of the page, but with your instruction it is not executed. I have done some tests and it works fine.

Thanks for everything.

Suggested topics

Topic Participants Replies Views Activity
General · by Jerry Hunt, 4 days ago
2 82 11 hours ago
General · by pamtbaau, 17 hours ago
1 55 16 hours ago
General · by Andy Miller, 1 day ago
0 45 1 day ago
General · by Marcel, 12 months ago
6 348 5 days ago
General · by Duc , 5 days ago
3 43 5 days ago