Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase font size with JavaScript around fixed floated images in CSS columns

I was searching for an html page, where i can acquire Font size of a text in a div to be increased using javascript and at the same time an image placed in that div should not be changed as an when the text size is increased. Below i am pasting the sample html page with a text div and image div with javascript to increase the font size. When we click on the Change font size button it will increase the font size at the same time the image placed inside that div will displace from its initial position. But I should place this image at the same position, no matter how the text size has increased and if the text has overflowed it should go to next column. Please help me to overcome this difficulty.

    <html>
<head>

<style type="text/css">
<!--

div#multicolumn4 {
    -moz-column-width: 150px;
    -moz-column-gap: 20px;
    -webkit-column-width: 250px;
    -webkit-column-gap: 20px;
    column-width: 150px;
    column-gap: 20px;
    height: 900px;
}


-->
</style>

<script>
  function changeFontSize(size)
  {
  debugger;
   var elms = document.getElementsByTagName("span");
   for(var i = 0;i < elms.length;i++)
   {
    var elmsHtml = elms[i].innerHTML;
    var widthFactor = parseInt(elms[i].style.fontSize);
    var FontSize = 0;
    var ln = elmsHtml.length;
    FontSize = Math.ceil(widthFactor +size);
    elms[i].style.fontSize = FontSize;
   }
  }
  function setFontSize(FontSize)
  {
   var elms = document.getElementsByTagName("span");
   for(var i = 0;i < elms.length;i++)
   {
    elms[i].style.fontSize = FontSize;
   }
  }
 </script>
</head>

<body>
    <div>


<div id="multicolumn4" >
<span style='font-size:10px;'>
<h1>The header of the columns</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla at turpis eget nibh ultricies dignissim. Duis luctus euismod turpis. Mauris augue. Aliquam facilisis semper elit. Pellentesque semper hendrerit arcu. Phasellus eleifend commodo justo. Aliquam orci urna, imperdiet sit amet, posuere in, lobortis et, risus. Integer interdum nonummy erat. Nullam tellus. Sed accumsan. Vestibulum orci ipsum, eleifend vitae, mollis vel, mollis sed, purus. Suspendisse mollis elit eu magna. Morbi egestas. Nunc leo ipsum, blandit ac, viverra quis, porttitor quis, dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>
</span>
<div><img id="Image-Maps_5201006280459541" src="images/im1.png" usemap="#Image-Maps_5201006280459541" border="0" width="192" height="256" alt="" />
<span style='font-size:10px;'>
<p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Vestibulum dui turpis, lobortis quis, euismod sed, consectetuer sit amet, nunc. Nam mi. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla at turpis eget nibh ultricies dignissim. Duis luctus euismod turpis. Mauris augue. Aliquam facilisis semper elit. Pellentesque semper hendrerit arcu. Phasellus eleifend commodo justo. Aliquam orci urna, imperdiet sit amet, posuere in, lobortis et, risus. Integer interdum nonummy erat. Nullam tellus. Sed accumsan. Vestibulum orci ipsum, eleifend vitae, mollis vel, mollis sed, purus. Suspendisse mollis elit eu magna. Morbi egestas. Nunc leo ipsum, blandit ac, viverra quis, porttitor quis, dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>

<p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Vestibulum dui turpis, lobortis quis, euismod sed, consectetuer sit amet, nunc. Nam mi. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla at turpis eget nibh ultricies dignissim. Duis luctus euismod turpis. Mauris augue. Aliquam facilisis semper elit. Pellentesque semper hendrerit arcu. Phasellus eleifend commodo justo. Aliquam orci urna, imperdiet sit amet, posuere in, lobortis et, risus. Integer interdum nonummy erat. Nullam tellus. Sed accumsan. Vestibulum orci ipsum, eleifend vitae, mollis vel, mollis sed, purus. Suspendisse mollis elit eu magna. Morbi egestas. Nunc leo ipsum, blandit ac, viverra quis, porttitor quis, dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>

<p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Vestibulum dui turpis, lobortis quis, euismod sed, consectetuer sit amet, nunc. Nam mi. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nulla at turpis eget nibh ultricies dignissim. Duis luctus euismod turpis. Mauris augue. Aliquam facilisis semper elit. Pellentesque semper hendrerit arcu. Phasellus eleifend commodo justo. Aliquam orci urna, imperdiet sit amet, posuere in, lobortis et, risus. Integer interdum nonummy erat. Nullam tellus. Sed accumsan. Vestibulum orci ipsum, eleifend vitae, mollis vel, mollis sed, purus. Suspendisse mollis elit eu magna. Morbi egestas. Nunc leo ipsum, blandit ac, viverra quis, porttitor quis, dui. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>

<p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Vestibulum dui turpis, lobortis quis, euismod sed, consectetuer sit amet, nunc. Nam mi. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>


</span>
        <p><button onclick="changeFontSize(1.0)">Change font size (+)</button></p>
        <p><button onclick="changeFontSize(-1.0)">Change font size (-)</button></p>
 </div>
 </div>
 </body>
</html>
like image 642
Krishna Avatar asked Nov 29 '25 15:11

Krishna


1 Answers

This type of layout question has been asked before quite a few times :-)

From a quick read of the links on that thread, it looks like it is not easy to do.

Edit: Right, this one has been bugging me. I figured it was possible with a small amount very large amount of complex JavaScript/jQuery and set about making a demo.

There is still some work to be done, since the <p> that contains the image has been left in a bad way (i.e. full of <span> elements). I also make no promises on the performance of this solution. It seems to work for me OK. Oh and also the Font + link will only work once as the actual size of the font it increases the text to is fixed.

That said, I would really try and find an alternate solution to your problem or even question why you need to fix an image position in this way. It is going against the normal browser re-flow and rules.

Edit: Improved demo that addresses the issues in the comments.

Edit 2: Wow, I did not know how complex the CSS3 column layout must be for browsers! Height is calculated in order to make the columns more or less equal and that means that when I detach the <img> the height is adjusted. This adjusted height will be different if the font-size increases and the <img> is not removed. It's just not possible to determine the height of the result before the <img> is removed and added.

That said, I have made it work with one major condition - that the column has a hard-coded height. I tried to make it work with a browser calculated height (as normal flow rules would dictate) but I think it might be very difficult without a lot more work. The only way I think this might work is moving the <img> element forwards one <span> (i.e. word) at a time until the correct position().top is reached. But that would be incredibly inefficient and probably slow the rendering down so much it will be unusable.

So, here is my final demo which is working in Chrome 11 for me. Sorry I could not reach a complete solution with variable height but as I, and others, have said it really is breaking all the browser layout rules!

Edit 3: When I said "final" demo I clearly didn't mean it. I accept your challenge to actually make this work properly with multiple images and I really hope that this time, I have got it. Please have a look at this new demo (working in Chrome12 for me) which works with the HTML you posted. I must admit that the JavaScript you posted was very complex. So I have re-factored everything to work with multiple images based on my original JavaScript.

Edit 4: Quite a lot of edits now… but I found the bug. For each font increment or decrement the images are moved in the flow and potentially a margin-top added to move the image back to it's original position. But I was not clearing this CSS before re-calculating the position on a subsequent font size change.

The key code added was:

// clear any existing marginTop added on the images
images.each(function() {
    $(this).css('marginTop', 0);
});

I also tidied up the JavaScript a bit more whilst I was there and fixed another bug with removing the <span> elements :-)

Updated jsFiddle demo

And just in case jsFiddle ever disappears, here is the complete solution as one HTML file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[
        $(function(){
            var fontSize = 15;

            // cannot store img.position().top or .left here because it is
            // before the browser has re-flowed the columns, therefore the
            // positions will be incorrect
            var imageTops = new Array;
            var imageLefts = new Array;

            $('#fontUp').click(function() {
                reflow(1);
            });

            $('#fontDown').click(function() {
                reflow(-1);
            });

            function reflow(fontSizeStep) {
                storeImagePositions();
                var fontLimitReached = changeFont(fontSizeStep);
                if (!fontLimitReached) {
                    moveImages();
                }
                return false;
            }

            function changeFont(step) {
                fontSize += step;

                var fontSizeLimitReached = true;

                if (fontSize > 30) {
                    fontSize = 30;
                } else if (fontSize < 15) {
                    fontSize = 15;
                } else {
                    fontSizeLimitReached = false;
                }

                if (!fontSizeLimitReached) {
                    $('p').css({fontSize: fontSize + 'px'});
                }

                return fontSizeLimitReached;
            }

            // initialize store of img top and left positions
            function storeImagePositions() {
                if (imageTops.length == 0) { // only do it once
                    $('img').each(function() {
                        var imgPosition = $(this).position();

                        imageTops.push(imgPosition.top);
                        imageLefts.push(imgPosition.left);
                    });
                }
            }

            function moveImages() {
                // bye bye images
                var images = $('img').detach();

                // clear any existing marginTop added on the images
                images.each(function() {
                    $(this).css('marginTop', 0);
                });


                // spanify paragraphs
                $('#column > p').each(function() {
                    $(this).html('<span>' + $(this).html().replace(/\s\s+/g).replace(/(\s)/g,'</span>$1<span>') + '</span>');
                });

                var imageIndex = 0;

                // iterate words, working out where we can move the img to in the flow and if
                // we find a match, increment the index so that as we continue the each()
                // the next image is evaluated for replacement
                $('#column > p span').each(function() {
                    var wordPosition = $(this).position();
                    var wordLeft = wordPosition.left;

                    if (wordLeft >= imageLefts[imageIndex]) {
                        var wordBottom = wordPosition.top + $(this).height();

                        if (wordBottom > imageTops[imageIndex]) {
                            $(this).before(images[imageIndex]); // move img before this word
                            var newImgTop = $(images[imageIndex]).position().top;
                            $(images[imageIndex]).css({marginTop: imageTops[imageIndex] - newImgTop + 'px'});
                            imageIndex++; // increment index so remainder spans are being evaluated against the next image
                        }
                    }
                });

                // reverse the "spanification"
                $('#column > p').each(function() {
                    $(this).html($(this).html().replace(/<\\?span>/g, '').trim());
                });
            }
        });
    //]]>
    </script>
    <style type="text/css">
    div#column {
        -moz-column-count:6;
        -webkit-column-count:3;
        column-count:3;
        -webkit-column-width:100px;
        -moz-column-width:100px;
        column-width:100px;
        height:500px;
    }

    p {
        margin:0;
        clear:left;
        font-size:15px;
        text-align:justify;
    }

    img {
        float:left;
    }
    </style>
</head>
<body>
    <div><a href="#" id="fontUp" style="margin-right:10px">Font +</a><a href="#" id="fontDown">Font -</a></div>
    <div id="column">
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. <img src="http://www.avatarblast.com/avatars/cool/yoda.jpg" title="yoda" alt="yoda"/>It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
        <p>The change of name from <img src="http://www.avatarblast.com/avatars/cool/yoda.jpg" title="yoda" alt="yoda"/> LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. The final choice of name caused confusion, giving the impression that the language was a spin-off of the Java programming language, and the choice has been characterized by many as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web-programming language. It has also been claimed that the language's name is the result of a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. Vivamus scelerisque ipsum ut justo. Pellentesque et ligula eu massa sagittis rutrum. In urna nibh, eleifend vel, suscipit ut, sagittis id, nunc.</p>
        <p>Nam ut sapien sed pede pulvinar rutrum. Nunc eu elit sed augue aliquet tincidunt. Morbi rutrum. Vestibulum dui turpis, lobortis quis, euismod sed, consectetuer sit amet, nunc. Nam mi. Fusce at nisl eu tortor bibendum eleifend. Sed ac metus. Phasellus nec elit. Morbi tortor nulla, tristique a, adipiscing at, consectetuer et, nisi. Nunc vel sapien sed risus hendrerit egestas. Vivamus turpis arcu, placerat eu, congue vel, commodo ut, nisl.</p>
        <p>Java EE includes several API specifications, such as JDBC, RMI, e-mail, JMS, web services, XML, etc., and defines how to coordinate them. Java EE also features some specifications unique to Java EE for components. These include Enterprise JavaBeans, Connectors, servlets, portlets (following the Java Portlet specification), JavaServer Pages and several web service technologies.<img src="http://www.avatarblast.com/avatars/cool/yoda.jpg" title="yoda" alt="yoda"/> This allows developers to create enterprise applications that are portable and scalable, and that integrate with legacy technologies. A Java EE application server can handle transactions, security, scalability, concurrency and management of the components that are deployed to it, in order to enable developers to concentrate more on the business logic of the components rather than on infrastructure and integration tasks.</p>
        <p>Java (Indonesian: Jawa) is an island of Indonesia. With a population of 136 million, it is the world's most populous island, and one of the most densely populated regions in the world. It is home to 60% of Indonesia's population. The Indonesian capital city, Jakarta, is in west Java.  Much of Indonesian history took place on Java; it was the centre of powerful Hindu-Buddhist empires, Islamic sultanates, the core of the colonial Dutch East Indies, and was at the centre of Indonesia's campaign for independence. The island dominates Indonesian social, political and economic life.</p>
    </div>
</body>
</html>
like image 91
andyb Avatar answered Dec 01 '25 04:12

andyb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!