Change image height based on div height

Discussion in 'JavaScript' started by sUpaL33tQwICKscoP3rzz__x, Aug 21, 2012.

  1. #1
    Hi everyone,

    I am trying to create a script that will change the height of an image to a set value depending on the height of a DIV. Basically, the DIV contains a collapsable table and the img is the page's background. I want the background to re-size based on how much of the table is visible. I hope this isn't too confusing.

    Here is my script:

    <script type="text/javascript"> function setbgsize() {
    var x = document.getElementById(lnkid);
    var bgimg = document.getElementById('GB');
    var tbh = document.getElementById('FAQtable');
    if(tbh.style.height = '1500px') { //All open
    bgimg.style.height = '1725px';
    }
    if(tbh.style.height = '1131px') { //Top 3 open
    bgimg.style.height = '1025px';
    }
    if(tbh.style.height = '803px') { //Top 2 open
    bgimg.style.height = '825px';
    }
    if(tbh.style.height = '639px') { //Top open
    bgimg.style.height = '500px';
    }
    if(tbh.style.height = '188px') { //None open
    bgimg.style.height = '450px';
    }
    }
    </script>

    Thanks
     
  2. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #2
    As a rule of thumb, resizing an image that way is a BAD idea -- unless it's something simple like a gradient it often looks like arse, it's accessibility rubbish (since it won't happen scripting off), only works if the element is an actual IMG tag (since you can't resize a background prior to CSS3) -- which being a background it is NOT content and as such has no business in a IMG tag.

    The 'ideal' answer is CSS3's background-size property.

    background-size:320px 100%;

    for example... makes it 320 wide and 100% the element height. Unfortunately, that won't work in IE8/lower.

    In general I just get the feeling you're over-thinking the solution to your problem -- it SOUNDS like a layout issue, and as such is none of javascripts business in the first place. Of course, it also looks like you're fixing the heights of layout elements, which 99.99% of the time is accessibility trash flushing accessibility and maintainability since it means no dynamic content or auto-adjusting for size.

    Really I'd have to see the image being scaled and the markup/layout/content you're dealing with to weigh in more... but like a lot of scripting tomfoolery, I suspect you're taking something simple and making it needlessly complex.
     
    deathshadow, Aug 22, 2012 IP