JavaScript
  Home arrow JavaScript arrow Page 6 - Building Rounded Corners With CSS and Java...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

Building Rounded Corners With CSS and JavaScript
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 38
    2005-01-03

    Table of Contents:
  • Building Rounded Corners With CSS and JavaScript
  • Our old friendly tables
  • The CSS approach
  • Working with fixed boxes
  • Nesting div elements
  • Using the DOM approach

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Building Rounded Corners With CSS and JavaScript - Using the DOM approach


    (Page 6 of 6 )

    If you’re not very familiar with the DOM, it’s just fine. For this article’s purposes, the only thing that we need to know is that any element of a Web document can be easily accessed via the DOM methods and modified according to our needs. This way, with the addition of JavaScript, it’s possible to manipulate the structure of a document after the browser has loaded it.

    Having defined briefly what the DOM is capable of doing, let’s work our way to improve the previous technique and get our rounded corners working again. The final solution uses only one <div> element for the original structure of the document, and requires some help from JavaScript to dynamically append three additional divs, which are needed to create the rounded corner effect.

    Our starting markup is the following:

    <div class="rounded">Content Goes Here</div>

    It’s noticeably reduced to only one <div>, being extremely efficient and avoiding the process of nesting different elements. That will be the task of a JavaScript function, which is listed below:

    <script language="javascript">

    function makeRounded() {
      /* finds all divs within the document */
     
      var divs=document.getElementsByTagName('div');
      var numDivs=divs.length;
     
      /* defines a new array for storing “rounded” divs */
      var roundedDivs= new Array();
     
      /*  looks for “rounded” divs and stores them in the array */
      for(i=0;i<numDivs;i++) {
        if(/\brounded\b/.test(divs[i].className)) {
          roundedDivs[roundedDivs.length]=divs[i];
        }
      }
      var numRoundedDivs=roundedDivs.length;

      /* appends the three divs needed for rounded corners */
      for(i=0;i<numRoundedDivs;i++) {
        /* access the bottom-right div (original div) */
        var brdiv=roundedDivs[i];

        /* creates top-left div */
        var tldiv=document.createElement('div');

        /* removes class name attribute from bottom-right div (original div)  */
        brdiv.className=brdiv.className.replace('rounded','');

    /* sets class name “rounded” to top-left div */
        tldiv.className='rounded';

        /* swaps bottom-right div (original div) with top-left div */
        brdiv.parentNode.replaceChild(tldiv,brdiv);

        /* creates top-right div inner node */
        trdiv=document.createElement('div');

        /* creates bottom-left div inner node */
        bldiv=document.createElement('div');

        /* appends top-left and top-right inner nodes in the document */
        tldiv.appendChild(trdiv);
        trdiv.appendChild(bldiv);

        /* appends bottom-right div (original div) back in the document */
        bldiv.appendChild(brdiv);
      }
    }
    /* calls the function after the page is loaded */
    window.onload=makeRounded;

    </script>

    The script looks fairly complex, but it’s not as intimidating as it seems. Let’s break down the code to see in detail how it works:

    The first part of the script loops over all of the <div> elements existing in the document, building a separate array containing all of the <div> elements with “rounded” as class name attribute.

    Then, once we’ve stored the “rounded” <div> elements as an array, we traverse it to access each element in turn, creating three additional divs and wrapping them around the original. Let’s see this in detail for a better understanding:

    var brdiv=roundedDivs[i];

    Here, we’re accessing in turn, to each original <div>, defined as our bottom right div. Next, we create the inner div of the four, defined as the top left div, with the following line:

    var tldiv=document.createElement('div');

    After that, we remove completely the class name attribute from the botton right div (the original div), since it will be applied later to the inner div of four, the top left div:

    brdiv.className=brdiv.className.replace('rounded','');
    tldiv.className='rounded';

    Now, let’s see the hardest and trickiest part. We have created in our original markup, the outermost div, which is used to apply the top right background image as well as the overall width of the box.

    With the line:

    brdiv.parentNode.replaceChild(tldiv,brdiv);

    We’re using a workaround to avoid some limitations of the W3C DOM. Since the DOM doesn’t provide a direct method for replacing a node in a document with another node, we must use the replaceChild() method to replace a child node with another. A handy way of replacing the actual node we’re searching for is to access its own parent using the parentNode property, and then use the replaceChild() method to swap it for something else. Maybe this sounds like we’re messing things up,  but we’re actually replacing our original node (the bottom right div) with the node we have just created (the top left div).

    The next steps consist of creating the two inner nodes (the top right and bottom left divs) and appending them in the document:

    trdiv=document.createElement('div');
    bldiv=document.createElement('div');
    tldiv.appendChild(trdiv);
    trdiv.appendChild(bldiv);

    Once we’ve created the new three <div> elements and inserted them in the document, all we need to do is re-insert the original node, in conjunction with its contents:

    bldiv.appendChild(brdiv);

    Still with me? Fine, because we’re almost done. At this point, the actual document tree is practically identical to that obtained with the four nested divs example, above described. Finally, here’s the code for the CSS:

    <style type="text/css">
    .rounded {
      width: 300px;
      background: #00f url(tl.gif) no-repeat top left;
    }
    .rounded div {
      background: transparent url(tr.gif) no-repeat top right;
    }
    .rounded div div {
      background: transparent url(bl.gif) no-repeat bottom left;
    }
    .rounded div div div{
      background: transparent url(br.gif) no-repeat bottom right;
      padding: 40px;
    }
    </style>

    The visual output for this technique is showed below:

    Building rounded corners with CSS and JavaScript

    We’ve achieved our rounded corners effect by manipulating the document structure, while keeping our markup set to a minimum expression. Also, we completely separated the JavaScript code from the HTML, and the CSS, getting a well-structured page. Not so bad, huh?

    Conclusion

    Our last technique is well supported by all the modern browsers and future versions that have full support for the CSS2 and DOM2 standards.

    In the meantime, we’ll have to settle down with the promising new features that CSS3 will provide for achieving rounded corners and similar effects. Unfortunately, there is a long time ahead before CSS3 support will be widely available. So let’s be patient, and use JavaScript as a great method for building rounded corners effects.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · As I've seen trough this article, building rounded corners that way is quite easy...
       · Nice article.I can see the smoothness in using JavaScript to make rounded corners,...
       · I liked the break-down a lot, and even though i think I'm gonna stay with the...
       · Hello,I think your point is good. The reason of having that Javascript design is...
       · Hello,Thank you for the comments. I agree about using only CSS for background...
       · the article is fine ...except for the need for gifs for each corner...i am sure...
       · Hi, Thnk you for the comment! I could have included the corner images, but I...
       · he was talking about the fact that you need .gif files at all to create this rounded...
       · Don't mean to cause problem, but right before your entry in google is...
       · If it's a decoration that your IE users can do without then you can make this easy....
       · Thanks for the comments on the article.Regarding the article that you...
       · Hi, I didn´t know about this technique. Thank you for sharing it. I think that it...
       · would be nice if he posted a solution how to create rounded corners without...
       · > Thnk you for the comment! I could have included the corner images, > but I...
       · Thank you for posting your comments here, and I hope you enjoy working with rounded...
       · What if your background image has a graient?
       · From the time I wrote this article, a few rounded corners techniques came up, which...
     

    JAVASCRIPT ARTICLES

    - Validating Digits and Dates with jQuery`s Va...
    - Validating Ranges, Emails, and URLs with jQu...
    - More Uses for the jQuery Tooltip Plug-in`s b...
    - Building Image-Based Tooltips with the jQuer...
    - Using the jQuery Tooltip Plug-in`s bodyHandl...
    - Using Rangelength, Min and Max with the Vali...
    - Using Minlength and Maxlength with the Valid...
    - Modifying Tooltip Coordinates with the jQuer...
    - Applying a Fade Out Effect with the jQuery T...
    - Tracking Mouse Movements with the jQuery Too...
    - Checking Online Forms with the Validator jQu...
    - Nested JavaScript Functions as Objects
    - The jQuery Tooltip Plug-in
    - Active Client Pages at the Server
    - ACP Tab Web Page







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    Stay green...Green IT