JavaScript - How to split background image using javascript

Asked By gowri shankar on 27-Jan-12 07:29 AM

      How to split background image with equal  height it is  with  in  div class <div class=""> using  javascript  and also how to apply single  color  to each section(height) of image using  javascript.
Jitendra Faye replied to gowri shankar on 27-Jan-12 07:32 AM

You could do it by setting the image as a background image and manipulating the size and background-position.

Here's how to do it using jQuery:

var img = /* get the image */
var width = Math.round(img.width() / 3.0);

var split = $('<div></div>')
    .css('background-image', 'url(' + img.attr('src') + ')')
    .css('background-position', '-' + width + 'px 0')
    .css('width', width + 'px')
    .css('height', img.height());


Try this and let me know.

D Company replied to gowri shankar on 27-Jan-12 07:36 AM
Hello friend,

best approch is use css.

like this

.container {background:url("...") 50% top repeat-x;}

look this very useful

[)ia6l0 iii replied to gowri shankar on 27-Jan-12 07:39 AM
You should not force such techniques to be executed by the client's browser. This isn't optimal way of doing it. 

Use a sprite image (the entire image) and control the image split through css elements. 

So have one style that captures the entire image as sprite into the background.

background:url(../images/sprite.png) no-repeat;

And then control the left and right portions through other css properties like:
.icon_left{width: 18px; background-position: -20px 0;}
.icon_right{background-position: 0 20px;}

Note that these are sample values used. You would have to change it according to your sprite image. 

And then apply these styles to your left and right div.

<div id="leftdiv" class="icon icon_left"></div>
<div id="rightdiv" class="icon icon_right"></div>

Hope this idea helps.
kalpana aparnathi replied to gowri shankar on 27-Jan-12 08:07 AM

Useful link: