<script language="javascript" type="text/javascript"> var divID = "MyDiv"; function CollapseExpand() { var divObject = document.getElementById(divID); var currentCssClass = divObject.className; if (divObject.className == "divVisible") divObject.className = "divHidden"; else divObject.className = "divVisible"; } </script>The divID variable holds the id value of the div you wish to collapse and expand. That value is "MyDiv." The rest of the code obtains the div's current CSS class name and switches it every time the code runs. The first time the code executes, it changes the div's class name to "divHidden." The second time it runs, it changes the class name back to "divVisible."
Wednesday, May 28, 2014
How to make simple Expand & Collapse DIV in JavaScript
Instructions
Add Div to Web Page
- Launch Notepad and open any of your HTML documents.
- Add this block of HTML code to the document's "body" section:
Div text
- This code creates a div and a button. The div contains a paragraph with text that reads: "Div text." Replace that text with anything you like. The "button" calls a JavaScript function when clicked. That function causes the div to switch between a collapsed state and an expanded state.
Locate the "id" and "class" properties in the div tag. To create an expanding and collapsing div, you must give the div an id value. In this example, that value is "MyDiv." The div also has a class property. In this instance, that property's value is "divVisible." That is the name of a CSS class defined in the next section.
Add CSS Classes and JavaScript
Add the following CSS code to the document's "head" section:
<style type="text/css"> .divVisible {display:block;} .divHidden {display:none;} </style>
This creates the "divVisible" class and another class named "divHidden." The "divVisible" class sets its display value to "block." The "block" value makes any HTML element that references the class visible and expands it to occupy space on the Web page. The "divHidden" class sets its display value to "none." Any HTML element referencing that class collapses and leaves no space behind.
- Add this JavaScript code below the CSS code:
- Save the HTML document, and open it in your browser. The paragraph containing your paragraph appears.
- Click the "Collapse/Expand" button. The text collapses. Click the button again to expand the text. Note how the button and other elements below the text move up when the text collapses and move down when the text expands.
Subscribe to:
Post Comments
(
Atom
)
Nie ader guna mana mana ker ?
ReplyDelete