Switching background image then resizing image to 'new height' with jQuery -


i have following:

html:

<div id="section-one" class="section">     <img id="section-one-img" style="width: 100%;" src="http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-pointers.jpg" />     <div id="section-one-headline">     <h1 class="main-headline"><span class="site-colour border-box">your local cctv company</span> <br /><p class="headline-desc">with on 80 installation teams nationwide</span></h1>     </div> </div> 

jquery:

jquery(document).ready(function() {     if (jquery(window).width() < 880) {     jquery('#section-one-img').attr("src", 'http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-880px.jpg');     }     var imgheight = jquery('#section-one-img').height();     jquery('#section-one-img').height(imgheight); }); 

although loads correct new image when screen size < 880, doesn't set new height of image (the bottom section of image cut off).

is there wrong in code fix this?

you have use load() function image after src changed:

fistly. element new image should created (dom) , calculate dimensions. can adjust them: take jsfiddle.net/csdtesting/81r4ktj4/1/ reason

implementation

jquery(document).ready(function() {     if (jquery(window).width() < 880) {           var img = 'http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-880px.jpg';                    var pic_real_width, pic_real_height;         $("<img/>") // make in memory copy of image avoid css issues             .attr("src", img)             .load(function() {                 pic_real_width = this.width;   // note: $(this).width() not                 pic_real_height = this.height; // work in memory images.                 /*alert(pic_real_width);                 alert(pic_real_height);*/             });        jquery('#section-one-img').attr("src", 'http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-880px.jpg');           jquery('#section-one-img').height(pic_real_height);     } }); 

hope helps!


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -