treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Question to experts: How to attach a Link to a background image?

  • How can I attach links to images that are set up as backgrounds in css? Is there a way to do achieve that? The reason why I want to set the images as backgrounds is because I dont want them to move durign browser scrolling.

    I will appreciate any hint or a referral to a good resource/article.

    Many thanks.



  • What do you want?

    If you scroll down that the background doesn't move?

    OR

    That your background has a link?
  • I want both :-)

    but I think I will try to use fixed position for my images to make sure they dont move
  • body {background: #fff url("/media/kfc/images/bg_sub.png") no-repeat fixed left top}
    The word 'fixed' fixes the background image, therefore it doesn't scroll.

    'How can I attach links to images that are set up as backgrounds in css?' - You will need an anchor link.
  • Am I right in assuming you want to be able to click the background image and then maybe display it on its own, or in a new tab/window? Like using Firefox: right click the background image and choose view background image?

    If you want to do it programmatically (scriptically??) this might be worth a try...

    Set an onclick event for the element with the background image that calls a javascript function to get the background image url from the CSS and then go to it...


    <div onclick="gotoBgImage(this);">
    ...
    <script>
    function gotoBgImage(el)
    {
    var style = window.getComputedStyle(el, null);
    url = style.backgroundImage.substring(5, style.backgroundImage.length - 2);
    location.href = url;
    }
    </script>


    getComputedStyle() is necessary if the background image has been set in a separate style file rather than an inline style - which is usually the case.

    The backgroundImage property is the string that sets the background image - something like url(....). The substring bit removes the url(" and ") from the backgroundImage property of the element leaving just the URL itself: http://www....whatever. Quick and dirty but works OK in Firefox.

    Any <a> tags in the element will still work but if you click on an otherwise inactive area you should get just the bg image.
  • I have not an idea how to achieve this. Many thanks to all of you