Nick Hadlee's Blog on SharePoint and Other Occasional Rants…


jQuery to Fix ‘Image Web Part’
July 18, 2009, 6:35 pm
Filed under: jQuery, SharePoint

While working on a mini-demo site today I managed to get distracted with a very minor (and irrelevant) component of the site. I felt compelled to find an elegant-ish resolution even though it served no practical purpose for the demo I was building. How often does that happen?

Image Web Part Sizing

The out-of-the-box Image Web Part is great for adding images to a site. Like all Web Parts it has some properties for changing the web parts behavior, but the problem is some of them don’t quite work as you might expect.

The width and height properties are the true target of this this post. Your initial expectation when you set them is the image displayed by the web part will resize to match the settings. This just isn’t how it works – if the image’s physical size is bigger than the Web Part then some ugly scroll-bars appear.

Image Without Resize

Figure 1: Standard ‘Image Web Part’ with the width property set.

Using a little bit of jQuery we can use these properties to apply the settings to our image as well. The following script can be added to the site using the Content Editor Web Part.

 <script type="text/javascript">
$(function(){
 $("img[id^='MSOImageWebPart_']").each(function(){
            var width = $(this).width();
            var parentDiv = $(this).parents("div.ms-WPBody");
            if(width > parentDiv.width()) {
                this.width = parentDiv.width();
            }
        });       
});
</script>  

Dynamically Resized Image

Figure 2: ‘Image Web Part’ that was resized with jQuery

Note: In this example I am only manipulating the width property of the image element. This leaves the browser to calculate the height of the image to keep everything in proportion. The height could be applied as well but then the image can start to look a little distorted):

See my previous post on jQuerywhich has some useful jQuery links including Jan Tielens excellent post on deploying jQuery to a site collection via a feature. Time to get back to building the demo now the distraction has been dealt with…

Advertisements

1 Comment so far
Leave a comment

SharePoint Development Weekly Roundup (21Jul)…

No suprises that #SP2010 is the big hitter again this week. ……

Trackback by SharePoint Blog by Jeremy Thake in Perth, Australia




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s



%d bloggers like this: