Search code examples
javascriptjqueryhtmlcss

Each portion of image having (or with) different id


I have an image with id myimage. It has a width of 300px and height 100px. each 100px wide portion has a unique color, like below:

------------------------
| red  | green | blue  |
------------------------

Is it possible to use each portion (having width & height 100px) with different id so that the image can be used as a button with different functions to each portion?

Answer only if it is possible and comment for others.

enter image description here


Solution

  • Set your image as a background image and give the parent div position:relative property. Then use nested divs with position:absolute each 100px apart from one another.

    <div id="wrap">
        <div class="first"></div>
        <div class="second"></div>
        <div class="third"></div>
    </div>
    
    #wrap{
        background:transparent url(...) no-repeat 0 0;
        width:300px;
        height:100px;
        position:relative;
    }
    
    .first, .second, .third{
        position:absolute;
        top:0;
        width:100px;
        height:100px;
    }
    .first{
        left:0;
    }
    .second{
        left:100px;
    }
    .third{
        left:200px;
    }
    

    Now using JQuery you can reference each part individually.

    $('.first').click(function(){ // this is the first part
     alert('first clicked')
    })
    

    Check working example at http://jsfiddle.net/PrMzr/