0

I am checking the device width and showing some option in menu. I need to check this while page loading and resizing. Because I need to check in devices in portrait and landscape view.

<script type="text/x-jsrender" id="option">
<ul class="dropdown-menu" role="menu">
{{if ~checkDevice()}}
        <li>
                <span class="btn"></span>
                Show
        </li>
{{/if}}
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$.views.helpers({
        checkDevice: function () {
            return window.innerWidth > 450;
        }
    });
});

This working correctly in on load. How to check this if condition on resize ?

Martin
  • 15,820
  • 4
  • 47
  • 56
Shesha
  • 1,857
  • 6
  • 21
  • 28
  • This answer might help you for the window resize [http://stackoverflow.com/questions/21626357/angularjs-event-on-window-innerwidth-size-change/21626400#21626400](http://stackoverflow.com/questions/21626357/angularjs-event-on-window-innerwidth-size-change/21626400#21626400) – Ana Liza Pandac Jun 10 '16 at 09:28

2 Answers2

1

In your example you are calling the checkDevice during JsRender rendering, so it will not get re-evaluated unless you trigger a refresh of the rendering on window resize, which will not be good for performance.

A better approach would be to drive an observable width or height property from the window onResize event.

$(window).resize(function () {
  $.observable(data).setProperty("width", window.innerWidth);
});

Then bind your template to the width or height values.

Here is a working jsfiddle: https://jsfiddle.net/BorisMoore/nm6Ljxph/

which uses

<script id="tmpl" type="text/x-jsrender">

Window width: {^{:width}}

<table><tbody>
  {^{if width<400 }}
    <tr><td>{{:first}}</td></tr><tr><td>{{:last}}</td></tr>
  {{else}}
    <tr><td>{{:first}}</td><td>{{:last}}</td></tr>
  {{/if}}
</tbody></table>

</script>

You can further help performance by using throttling or debouncing. The jsfiddle has a commented out debounce approach you can use...

BorisMoore
  • 8,444
  • 1
  • 16
  • 27
0

You can bind events to window resize with jQuery like this

$(window).resize(function(){

        //Call the function here
    });
});
Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69