convert javascript to jquery .width

96 views Asked by At

I'm using this script to load small or large images depending on the screen width.

    <script>
var jt_width = screen.width;
//var jt_height = screen.height;
if (jt_width < 361) {document.write('<div class="small-image"><img src="http://www.example.com/small-image.jpg" alt="small image alt"></div>') } else { document.write('<div class="large-image"><img src="http://www.example.com/large-image.jpg" alt="large image alt"></div>')};
</script>

The disadvantage is that on a mobile phone it doesn't change on the fly when someone goes from portrait to landscape, and I want to use jquery to do this.

I read online about different possibilities like using window.outerWidth or .width() and I understood that .width() is the best solution in terms of browser compatibility.

I would like to convert the script above to a jquery version, but since I hardly know anything about javascript I don't know how to do this. This is what I have

function load(){
    w.value = $(window).width();
    h.value = $(window).height();
}

How can I get the same output using jquery?

2

There are 2 answers

5
thesublimeobject On

Your new script won't help the responsize-ness of the script. You need to add a listener:

<script>
var jt_width = screen.width;
function doAThing() {
  if (jt_width < 361) {
    document.write('<div class="small-image"><img src="http://www.example.com/small-image.jpg" alt="small image alt"></div>') } else { document.write('<div class="large-image"><img src="http://www.example.com/large-image.jpg" alt="large image alt"></div>')
  };
}

doAThing();
window.addEventListener('resize', doAThing);
</script>

EDIT: I'm pretty sure 'resize' works fine for orientation, but if you test it and it's not working well you could also add a orientationchange listener on the function as well:

window.addEventListener('orientationchange', doAThing);

2
prashant gedam On

This is an implementation using jquery:

$( window ).resize( function ( ) { 
     var width = $( window ).width( );
     var height=$( window ).height( );
     /**on resize you can change your content or code based on your condition*/
});
/*This event will be triggered when the window size will change */