How to display center part of an image using jquery?

Css Displaying only center part of image using jQuery
How to display center part of an image using jquery?
Resize and Center image with jQuery

This article will show you how to display center part of image using jQuery. e.g. if you wnat to show 100X100 pixel center part of image.

basically we are using “background-position : left top” to set position of image, at runtime get the image height and width and calculate left and top offset.

var Left = parseInt((parseInt(imgWidth) – 100) / 2);
var top = parseInt((parseInt(imgHeight) – 100) / 2);

and set new css using jQuery

here is code

</pre>
<script type="text/javascript" >
 $(document).ready(function () {
 var img = document.getElementById('imageid');
 var width = img.clientWidth;
 var height = img.clientHeight;
 var url = img.src;

var Left = parseInt((parseInt(width) - 100) / 2);
 var top = parseInt((parseInt(height) - 100) / 2);
 Left = "-" + Left + "px";
 top = "-" + top + "px";
 var para = Left + " " + top;

 $('li#nav').addClass('list-style');

$("#myDiv").css({ "background-image": "url(" + url + ")",
 "background-repeat": "no-repeat", "background-position": '' + para + '',
 "width": "100px", "height": "100px", "background-color": "blue"
 });
 });

<div id="myDiv"></div>
 <img id="imageid" src="../../Images/india-flag.jpg" />
</script>

<span style="font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 18px;">

 

Advertisements
This entry was posted in jQuery and tagged , . Bookmark the permalink.

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