trying to collapse text [duplicate] - javascript

I have created a list on my site. This list is created by a foreach loop that builds with information from my database. Each item is a container with different sections, so this is not a list like 1, 2, 3... etc. I am listing repeating sections with information. In each section, there is a subsection. The general build is as follows:
<div>
<fieldset class="majorpoints" onclick="majorpointsexpand($(this).find('legend').innerHTML)">
<legend class="majorpointslegend">Expand</legend>
<div style="display:none" >
<ul>
<li></li>
<li></li>
</ul>
</div>
</div>
So, I am trying to call a function with onclick="majorpointsexpand($(this).find('legend').innerHTML)"
The div I am trying to manipulate is style="display:none" by default, and I want to use javascript to make it visible on click.
The "$(this).find('legend').innerHTML" is attempting to pass, in this case, "Expand" as an argument in the function.
Here is the javascript:
function majorpointsexpand(expand)
{
if (expand == "Expand")
{
document.write.$(this).find('div').style = "display:inherit";
document.write.$(this).find('legend').innerHTML = "Collapse";
}
else
{
document.write.$(this).find('div').style = "display:none";
document.write.$(this).find('legend').innerHTML = "Expand";
}
}
I am almost 100% sure my problem is syntax, and I don't have much of a grasp on how javascript works.
I do have jQuery linked to the document with:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
In the <head></head> section.

Okay, so you've got two options here :
Use jQuery UI's accordion - its nice, easy and fast. See more info here
Or, if you still wanna do this by yourself, you could remove the fieldset (its not semantically right to use it for this anyway) and create a structure by yourself.
Here's how you do that. Create a HTML structure like this :
<div class="container">
<div class="header"><span>Expand</span>
</div>
<div class="content">
<ul>
<li>This is just some random content.</li>
<li>This is just some random content.</li>
<li>This is just some random content.</li>
<li>This is just some random content.</li>
</ul>
</div>
</div>
With this CSS: (This is to hide the .content stuff when the page loads.
.container .content {
display: none;
padding : 5px;
}
Then, using jQuery, write a click event for the header.
$(".header").click(function () {
$header = $(this);
//getting the next element
$content = $header.next();
//open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
$content.slideToggle(500, function () {
//execute this after slideToggle is done
//change text of header based on visibility of content div
$header.text(function () {
//change text based on condition
return $content.is(":visible") ? "Collapse" : "Expand";
});
});
});
Here's a demo : http://jsfiddle.net/hungerpain/eK8X5/7/

how about:
jQuery:
$('.majorpoints').click(function(){
$(this).find('.hider').toggle();
});
HTML
<div>
<fieldset class="majorpoints">
<legend class="majorpointslegend">Expand</legend>
<div class="hider" style="display:none" >
<ul>
<li>cccc</li>
<li></li>
</ul>
</div>
</div>
Fiddle
This way you are binding the click event to the .majorpoints class an you don't have to write it in the HTML each time.

You might want to give a look at this simple Javascript method to be invoked when clicking on a link to make a panel/div expande or collapse.
<script language="javascript">
function toggle(elementId) {
var ele = document.getElementById(elementId);
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
</script>
You can pass the div ID and it will toggle between display 'none' or 'block'.
Original source on snip2code - How to collapse a div in html

So, first of all, your Javascript isn't even using jQuery. There are a couple ways to do this. For example:
First way, using the jQuery toggle method:
<div class="expandContent">
Click Here to Display More Content
</div>
<div class="showMe" style="display:none">
This content was hidden, but now shows up
</div>
<script>
$('.expandContent').click(function(){
$('.showMe').toggle();
});
</script>
jsFiddle: http://jsfiddle.net/pM3DF/
Another way is simply to use the jQuery show method:
<div class="expandContent">
Click Here to Display More Content
</div>
<div class="showMe" style="display:none">
This content was hidden, but now shows up
</div>
<script>
$('.expandContent').click(function(){
$('.showMe').show();
});
</script>
jsFiddle: http://jsfiddle.net/Q2wfM/
Yet a third way is to use the slideToggle method of jQuery which allows for some effects. Such as $('#showMe').slideToggle('slow'); which will slowly display the hidden div.

Many problems here
I've set up a fiddle that works for you: http://jsfiddle.net/w9kSU/
$('.majorpointslegend').click(function(){
if($(this).text()=='Expand'){
$('#mylist').show();
$(this).text('Colapse');
}else{
$('#mylist').hide();
$(this).text('Expand');
}
});

try jquery,
<div>
<a href="#" class="majorpoints" onclick="majorpointsexpand(" + $('.majorpointslegend').html() + ")"/>
<legend class="majorpointslegend">Expand</legend>
<div id="data" style="display:none" >
<ul>
<li></li>
<li></li>
</ul>
</div>
</div>
function majorpointsexpand(expand)
{
if (expand == "Expand")
{
$('#data').css("display","inherit");
$(".majorpointslegend").html("Collapse");
}
else
{
$('#data').css("display","none");
$(".majorpointslegend").html("Expand");
}
}

Here there is my example of animation a staff list with expand a description.
<html>
<head>
<style>
.staff { margin:10px 0;}
.staff-block{ float: left; width:48%; padding-left: 10px; padding-bottom: 10px;}
.staff-title{ font-family: Verdana, Tahoma, Arial, Serif; background-color: #1162c5; color: white; padding:4px; border: solid 1px #2e3d7a; border-top-left-radius:3px; border-top-right-radius: 6px; font-weight: bold;}
.staff-name { font-family: Myriad Web Pro; font-size: 11pt; line-height:30px; padding: 0 10px;}
.staff-name:hover { background-color: silver !important; cursor: pointer;}
.staff-section { display:inline-block; padding-left: 10px;}
.staff-desc { font-family: Myriad Web Pro; height: 0px; padding: 3px; overflow:hidden; background-color:#def; display: block; border: solid 1px silver;}
.staff-desc p { text-align: justify; margin-top: 5px;}
.staff-desc img { margin: 5px 10px 5px 5px; float:left; height: 185px; }
</style>
</head>
<body>
<!-- START STAFF SECTION -->
<div class="staff">
<div class="staff-block">
<div class="staff-title">Staff</div>
<div class="staff-section">
<div class="staff-name">Maria Beavis</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Maria earned a Bachelor of Commerce degree from McGill University in 2006 with concentrations in Finance and International Business. She has completed her wealth Management Essentials course with the Canadian Securities Institute and has worked in the industry since 2007.</p>
</div>
<div class="staff-name">Diana Smitt</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Diana joined the Diana Smitt Group to help contribute to its ongoing commitment to provide superior investement advice and exceptional service. She has a Bachelor of Commerce degree from the John Molson School of Business with a major in Finance and has been continuing her education by completing courses.</p>
</div>
<div class="staff-name">Mike Ford</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Mike: A graduate of École des hautes études commerciales (HEC Montreal), Guillaume holds the Chartered Investment Management designation (CIM). After having been active in the financial services industry for 4 years at a leading competitor he joined the Mike Ford Group.</p>
</div>
</div>
</div>
<div class="staff-block">
<div class="staff-title">Technical Advisors</div>
<div class="staff-section">
<div class="staff-name">TA Elvira Bett</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Elvira has completed her wealth Management Essentials course with the Canadian Securities Institute and has worked in the industry since 2007. Laura works directly with Caroline Hild, aiding in revising client portfolios, maintaining investment objectives, and executing client trades.</p>
</div>
<div class="staff-name">TA Sonya Rosman</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Sonya has a Bachelor of Commerce degree from the John Molson School of Business with a major in Finance and has been continuing her education by completing courses through the Canadian Securities Institute. She recently completed her Wealth Management Essentials course and became an Investment Associate.</p>
</div>
<div class="staff-name">TA Tim Herson</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Tim joined his father’s group in order to continue advising affluent families in Quebec. He is currently President of the Mike Ford Professionals Association and a member of various other organisations.</p>
</div>
</div>
</div>
</div>
<!-- STOP STAFF SECTION -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript"><!--
//<![CDATA[
$('.staff-name').hover(function() {
$(this).toggleClass('hover');
});
var lastItem;
$('.staff-name').click(function(currentItem) {
var currentItem = $(this);
if ($(this).next().height() == 0) {
$(lastItem).css({'font-weight':'normal'});
$(lastItem).next().animate({height: '0px'},400,'swing');
$(this).css({'font-weight':'bold'});
$(this).next().animate({height: '300px',opacity: 1},400,'swing');
} else {
$(this).css({'font-weight':'normal'});
$(this).next().animate({height: '0px',opacity: 1},400,'swing');
}
lastItem = $(this);
});
//]]>
--></script>
</body></html>
Fiddle

Take a look at toggle() jQuery function :
http://api.jquery.com/toggle/
Also, innerHTML jQuery Function is .html().

Since you have jQuery on the page, you can remove that onclick attribute and the majorpointsexpand function. Add the following script to the bottom of you page or, preferably, to an external .js file:
$(function(){
$('.majorpointslegend').click(function(){
$(this).next().toggle().text( $(this).is(':visible')?'Collapse':'Expand' );
});
});
This solutionshould work with your HTML as is but it isn't really a very robust answer. If you change your fieldset layout, it could break it. I'd suggest that you put a class attribute in that hidden div, like class="majorpointsdetail" and use this code instead:
$(function(){
$('.majorpoints').on('click', '.majorpointslegend', function(event){
$(event.currentTarget).find('.majorpointsdetail').toggle();
$(this).text( $(this).is(':visible')?'Collapse':'Expand' );
});
});
Obs: there's no closing </fieldset> tag in your question so I'm assuming the hidden div is inside the fieldset.

If you used the data-role collapsible e.g.
<div id="selector" data-role="collapsible" data-collapsed="true">
html......
</div>
then it will close the the expanded div
$("#selector").collapsible().collapsible("collapse");

Pure javascript allowing only one expanded div at a time. It allows multi-level sub-expanders. The html only need the expanders contents. The javascript will create the expanders headers with the titles form the content data attribute and a svg arrow.
<style>
/* expanders headers divs */
.expanderHead {
color: white;
background-color: #1E9D8B;
border: 2px solid #1E9D8B;
margin-top: 9px;
border-radius: 6px;
padding: 3px;
padding-left: 9px;
cursor: default;
font-family: Verdana;
font-size: 14px;
}
.expanderHead:first-child {
margin-top: 0 !important;
}
.expanderBody:last-child {
margin-bottom: 0 !important;
}
/* expanders svg arrows */
.expanderHead svg > g > path {
fill: none;
stroke: white;
stroke-width: 2;
stroke-miterlimit: 5;
pointer-events: stroke;
}
/* expanders contents divs */
.expanderBody {
border: 2px solid #1E9D8B;
border-top: 0;
background-color: white;
border-top-left-radius: 0;
border-top-right-radius: 0;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
padding: 6px;
font-family: Verdana;
font-size: 12px;
}
/* widget window */
.widget {
width: 400px;
background-color: white;
padding: 9px;
border: 2px solid #1E9D8B;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
}
</style>
<div class="widget">
<div data-title="expander 1" class="expanderBody">
expander 1 content
</div>
<div data-title="expander 2" class="expanderBody">
expander 2 content
</div>
<div data-title="expander 3" class="expanderBody">
<div>
expander 3 content
</div>
<div data-title="expander 3.1" class="expanderBody">
expander 3.1 content
</div>
<div data-title="expander 3.2" class="expanderBody">
expander 3.2 content
</div>
<div data-title="expander 3.3" class="expanderBody">
expander 3.3 content
</div>
</div>
</div>
<script>
document.querySelectorAll(".expanderBody").forEach(item => {
if (item.dataset.title) {
// create expander header
let divHeader = document.createElement("div");
divHeader.className = "expanderHead";
divHeader.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 5 5 L 10 1'/><path d='M 1 1 L 5 5'/></g></svg> <span>" + item.dataset.title + "</span>";
// expander click event
divHeader.addEventListener("click", function () {
// open / close expander
for (let i = 0; i < this.parentNode.children.length; i++) {
let expander = this.parentNode.children[i];
// check if it's expander header
if (expander.className == "expanderHead") {
if (expander == this && expander.nextElementSibling.style.display == "none") {
// open expander body
expander.nextElementSibling.style.display = "";
expander.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 1 5 L 5 1'/><path d='M 5 1 L 10 5'/></g></svg> <span>" + expander.nextElementSibling.dataset.title + "</span>";
expander.style.borderBottomLeftRadius = "0";
expander.style.borderBottomRightRadius = "0";
}
else {
// close expander body
expander.nextElementSibling.style.display = "none";
expander.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 5 5 L 10 1'/><path d='M 1 1 L 5 5'/></g></svg> <span>" + expander.nextElementSibling.dataset.title + "</span>";
expander.style.borderBottomLeftRadius = "6px";
expander.style.borderBottomRightRadius = "6px";
}
}
}
}, true);
item.parentNode.insertBefore(divHeader, item);
item.style.display = "none";
}
});
</script>

Check out Jed Foster's Readmore.js library.
It's usage is as simple as:
$(document).ready(function() {
$('article').readmore({collapsedHeight: 100});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://fastcdn.org/Readmore.js/2.1.0/readmore.min.js" type="text/javascript"></script>
<article>
<p>From this distant vantage point, the Earth might not seem of any particular interest. But for us, it's different. Consider again that dot. That's here. That's home. That's us. On it everyone you love, everyone you know, everyone you ever heard of, every human being who ever was, lived out their lives. The aggregate of our joy and suffering, thousands of confident religions, ideologies, and economic doctrines, every hunter and forager, every hero and coward, every creator and destroyer of civilization, every king and peasant, every young couple in love, every mother and father, hopeful child, inventor and explorer, every teacher of morals, every corrupt politician, every "superstar," every "supreme leader," every saint and sinner in the history of our species lived there – on a mote of dust suspended in a sunbeam.</p>
<p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>
<p>Here's how it is: Earth got used up, so we terraformed a whole new galaxy of Earths, some rich and flush with the new technologies, some not so much. Central Planets, them was formed the Alliance, waged war to bring everyone under their rule; a few idiots tried to fight it, among them myself. I'm Malcolm Reynolds, captain of Serenity. Got a good crew: fighters, pilot, mechanic. We even picked up a preacher, and a bona fide companion. There's a doctor, too, took his genius sister out of some Alliance camp, so they're keeping a low profile. You got a job, we can do it, don't much care what it is.</p>
<p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>
</article>
Here are the available options to configure your widget:
{
speed: 100,
collapsedHeight: 200,
heightMargin: 16,
moreLink: 'Read More',
lessLink: 'Close',
embedCSS: true,
blockCSS: 'display: block; width: 100%;',
startOpen: false,
// callbacks
blockProcessed: function() {},
beforeToggle: function() {},
afterToggle: function() {}
},
Use can use it like:
$('article').readmore({
collapsedHeight: 100,
moreLink: 'Continue reading...',
});
I hope it helps.

Using Pure Javascript
const collapsableBtn = document.querySelectorAll('.collapsable-toggle');
for (let index = 0; index < collapsableBtn.length; index++) {
collapsableBtn[index].addEventListener('click', function(e) {
// e.preventDefault();
e.stopImmediatePropagation();
iterateElement = this;
getCollapsableParent = iterateElement.parentElement;
if(getCollapsableParent.classList.contains('show')) {
getCollapsableParent.classList.remove('show')
iterateElement.innerText = iterateElement.getAttribute('data-onCloseText');
} else {
getCollapsableParent.classList.add('show');
iterateElement.innerText = iterateElement.getAttribute('data-onOpenText');
}
})
}
.collapsable-container #expand {
display:none;
}
.collapsable-container.show #expand {
display:block;
}
<div class="collapsable-container">
Show First Content
<div id="expand">
This is some Content
</div>
</div>
<div class="collapsable-container">
Show Second Content
<div id="expand">
This is some Content
</div>
</div>

Related

Trying to get jQuery to change a different img src when clicked

I've got 2 seperate divs that change background img src when clicked which works fine, but I would like it to change the other image its present with. E.g. div 1 is pressed and becomes "open", if div2 is "open" it then becomes closed. My jQuery is rather limited and have it functioning where it can change the image, but need to figure out how to apply the "closed" class to images that haven't just been clicked. Ideally it would use the attr() so I can add more later.
jQuery
$(".box").on("click", function() {
// need to make this function select the other div.
if ($(this).hasClass("closed")) {
$(this).addClass("open").removeClass("closed");
} else {
$(this).addClass("closed").removeClass("open");
}
var id = $(this).attr("data-id");
$(this).toggleClass("open");
$(".hideDivs").hide();
$("#" + id).show();
});
.container {
width: 640px;
height: 450px;
background-color: #eee;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
}
.text-primary {
font-size: 14px;
text-align: center;
margin-bottom: 5px;
}
.box {
cursor: pointer;
width: 90px;
height: 180px;
display:block;
margin:auto;
background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/closed_vo1pn2.png");
}
.open {
background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/open_ihcmuz.png");
}
.closed {
background-image: url("http://res.cloudinary.com/dez1tdup3/image/upload/v1499052120/closed_vo1pn2.png");
}
.hideDivs {
display: none;
}
.panel-body {
padding: 10px;
margin-top: 5px;
}
.title {
font-weight: bold;
font-size: 14px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-xs-6">
<div class="box" data-id="divId1">
</div>
</div>
<div class="col-xs-6">
<div class="box" data-id="divId2">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="panel panel-default hideDivs" id="divId1">
<div class="panel-body">
<span class="title">Practices for safe packaging of cooked foods</span>
<ul>
<li>Label and date all food.</li>
<li>Package high-risk food in small batches for refrigeration and return to refrigerated storage as soon as possible (within 20 minutes).</li>
<li>Store packaging products in a clean environment and protect from contamination.</li>
</ul>
</div>
</div>
<div class="panel panel-default hideDivs" id="divId2">
<div class="panel-body">
<span class="title">Practices for safe freezing of cooked foods</span>
<ul>
<li>When packaging food for freezing, cover or wrap, label and date (production and freezing date) all foods.</li>
<li>Freeze food in small quantities to ensure food is frozen quickly.</li>
<li>Do not overload freezer units and ensure air can circulate.</li>
<li>Do not freeze foods that have been cooked then refrigerated and reheated.</li>
</ul>
</div>
</div>
</div>
</div>
</div>
Please check the jsfiddle and let me know if you are looking something like this.
https://jsfiddle.net/314sybno/2/
$(".box").on("click", function() {
var id = $(this).attr("data-id");
if( id === 'divId1') {
$('div[data-id="divId2"]').addClass('closed').removeClass('open');
} else {
$('div[data-id="divId1"]').addClass('closed').removeClass('open');
}
// need to make this function select the other div.
if ($(this).hasClass("closed")) {
$(this).addClass("open").removeClass("closed");
} else {
$(this).addClass("closed").removeClass("open");
}
$(".hideDivs").hide();
$("#" + id).show();
});
This might be a better approach:
$(".box").on("click", function() {
// Hide all detail divs
$(".hideDivs").hide();
if ($(this).is(".closed")) {
// Close other open boxes
$(".box.open").removeClass("open").addClass("closed");
// Open this box and show the corresponding details div
$(this).removeClass("closed").addClass("open");
var id = $(this).attr("data-id");
$("#" + id).show();
} else {
// Close this box
$(this).removeClass("open").addClass("closed");
}
});
Also, I would recommend changing your HTML to have your 'box' elements also have a 'closed' class, so you do not repeat/need the CSS background attribute on the 'box' class.
See it working on this fiddle

Change height of child element on button/link press using ::before

I've got an Org Chart that will run on mobile devices nearly completely different from how it runs on desktop. Everything is as it should be with one minor problem. My Org Chart features the ability to click a person which then slides an accordion down to provide more information about that particular person along with contact information. This feature is great on desktop but when it runs to mobile, my connectors are based on fixed values in the CSS. I need the ::before height to be changed when the accordion is extended to counter this. I've provided photos below for further clarification.
Images of before and after: http://imgur.com/a/x7JSn
Now my main concern is that I've put myself in a position where I'll have to write totally different functions for each element in order for that particular element to connect.
Here's how my HTML is laid out:
<ul>
<li class="director">
<div id="ss_menu">
<a href="javascript:void(0);" class="ss_button">
<span class="title">Director </span><br/>
<span class="sm-hide">Name of Person</span>
</a>
<div class="ss_content">
<img src="img/person.jpg"
width="70px"
style="border: 1px solid #000;"/><br/>
Telephone: 555-555-5555<br/>
Email: emailaddress#email.com<br/>
Room: A123<br/>
Mail Stop: A123
</div>
</div>
<ul>
<li>
<div id="ss_menu">
<a href="javascript:void(0);" class="ss_button">
<span class="title">Assistant to the Director </span><br/>
<span class="sm-hide">Name of Person</span>
</a>
<div class="ss_content">
<img src="img/person.jpg"
width="70px"
style="border: 1px solid #000;"/><br/>
Telephone: 555-555-5556<br/>
Email: emailaddress#email.com<br/>
Room: A124<br/>
Mail Stop: A124
</div>
</div>
<ul>
<! -- THE CODE CONTINUES FOR A WHILE BUT IS LAID OUT THE SAME WAY -->
And then here is the general layout of the vertical lines using the ::before keyword:
.director::before {
content: "";
border-left: 1px solid #ccc;
position: absolute;
height: 165px;
margin-left: -30px;
z-index: -1;
}
.deputydirector::before {
content: "";
border-left: 1px solid #ccc;
position: absolute;
height: 1442px;
margin-left: -30px;
z-index: -1;
}
I'm essentially trying to increase the height of the vertical lines by the amount that the accordion opens.
Lastly here is the jQuery code I'm using for the accordion which I'd like to use as a catch-all for managing my vertical lines as well.
jQuery(function() {
jQuery('.ss_button').on('click',function() {
jQuery('.ss_content').slideUp('fast');
jQuery(this).next('.ss_content').slideDown('fast');
});
});

HTML/Javascript spoiler script not working in IE (Show/Hide)

<div id="z1" onclick="document.getElementById('q1').style.display=''; document.getElementById('z1').style.display='none';" style="border:solid 1px; background- color: #DDDDDD; width:936px; height:auto; margin-left:0px;margin-right:0px;">
<h2> Pg. 419-423, problems 8-14 even, 20-30 odd, AYP 1-10</h2></div>
<div id="q1" onclick="document.getElementById('q1').style.display='none'; document.getElementById('z1').style.display='';" style="display:none; border:solid 1px; background-color: #DDDDDD; width:938px; height:auto;margin-left:0px;margin-right:0px;">
<h2> Pg. 419-423, problems 8-14 even, 20-30 odd, AYP 1-10</h2>
</br>
<img src="http://www.rediker.com/reports/samples/Attendance-Period/Homework-Assignment- form.jpg"></img></div>
The above script is what I planned on using to create a spoiler. Basically, when the user clicks on the z1 element, it hides itself and shows the q1 element, and vice-versa. It works on all browsers besides IE. Linking Jquery would be a small liability.
I think this is what you're looking for. You're missing to add display: block
Change this
document.getElementById('z1').style.display='';
to
document.getElementById('z1').style.display='block';
You should think about cleaning your code.
HTML:
<div id="z1" onclick="aa()"></div>
<div id="q1" onclick="bb()">
<img src="http://www.rediker.com/reports/samples/Attendance-Period/Homework-Assignment-form.jpg"/>
</div>
JS:
function aa() {
document.getElementById('q1').style.display = 'block';
document.getElementById('z1').style.display = 'none';
}
function bb() {
document.getElementById('q1').style.display = 'none';
document.getElementById('z1').style.display = 'block';
}
Working JSfiddle

How can I expand and collapse a <div> using javascript?

I have created a list on my site. This list is created by a foreach loop that builds with information from my database. Each item is a container with different sections, so this is not a list like 1, 2, 3... etc. I am listing repeating sections with information. In each section, there is a subsection. The general build is as follows:
<div>
<fieldset class="majorpoints" onclick="majorpointsexpand($(this).find('legend').innerHTML)">
<legend class="majorpointslegend">Expand</legend>
<div style="display:none" >
<ul>
<li></li>
<li></li>
</ul>
</div>
</div>
So, I am trying to call a function with onclick="majorpointsexpand($(this).find('legend').innerHTML)"
The div I am trying to manipulate is style="display:none" by default, and I want to use javascript to make it visible on click.
The "$(this).find('legend').innerHTML" is attempting to pass, in this case, "Expand" as an argument in the function.
Here is the javascript:
function majorpointsexpand(expand)
{
if (expand == "Expand")
{
document.write.$(this).find('div').style = "display:inherit";
document.write.$(this).find('legend').innerHTML = "Collapse";
}
else
{
document.write.$(this).find('div').style = "display:none";
document.write.$(this).find('legend').innerHTML = "Expand";
}
}
I am almost 100% sure my problem is syntax, and I don't have much of a grasp on how javascript works.
I do have jQuery linked to the document with:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
In the <head></head> section.
Okay, so you've got two options here :
Use jQuery UI's accordion - its nice, easy and fast. See more info here
Or, if you still wanna do this by yourself, you could remove the fieldset (its not semantically right to use it for this anyway) and create a structure by yourself.
Here's how you do that. Create a HTML structure like this :
<div class="container">
<div class="header"><span>Expand</span>
</div>
<div class="content">
<ul>
<li>This is just some random content.</li>
<li>This is just some random content.</li>
<li>This is just some random content.</li>
<li>This is just some random content.</li>
</ul>
</div>
</div>
With this CSS: (This is to hide the .content stuff when the page loads.
.container .content {
display: none;
padding : 5px;
}
Then, using jQuery, write a click event for the header.
$(".header").click(function () {
$header = $(this);
//getting the next element
$content = $header.next();
//open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
$content.slideToggle(500, function () {
//execute this after slideToggle is done
//change text of header based on visibility of content div
$header.text(function () {
//change text based on condition
return $content.is(":visible") ? "Collapse" : "Expand";
});
});
});
Here's a demo : http://jsfiddle.net/hungerpain/eK8X5/7/
how about:
jQuery:
$('.majorpoints').click(function(){
$(this).find('.hider').toggle();
});
HTML
<div>
<fieldset class="majorpoints">
<legend class="majorpointslegend">Expand</legend>
<div class="hider" style="display:none" >
<ul>
<li>cccc</li>
<li></li>
</ul>
</div>
</div>
Fiddle
This way you are binding the click event to the .majorpoints class an you don't have to write it in the HTML each time.
You might want to give a look at this simple Javascript method to be invoked when clicking on a link to make a panel/div expande or collapse.
<script language="javascript">
function toggle(elementId) {
var ele = document.getElementById(elementId);
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
</script>
You can pass the div ID and it will toggle between display 'none' or 'block'.
Original source on snip2code - How to collapse a div in html
So, first of all, your Javascript isn't even using jQuery. There are a couple ways to do this. For example:
First way, using the jQuery toggle method:
<div class="expandContent">
Click Here to Display More Content
</div>
<div class="showMe" style="display:none">
This content was hidden, but now shows up
</div>
<script>
$('.expandContent').click(function(){
$('.showMe').toggle();
});
</script>
jsFiddle: http://jsfiddle.net/pM3DF/
Another way is simply to use the jQuery show method:
<div class="expandContent">
Click Here to Display More Content
</div>
<div class="showMe" style="display:none">
This content was hidden, but now shows up
</div>
<script>
$('.expandContent').click(function(){
$('.showMe').show();
});
</script>
jsFiddle: http://jsfiddle.net/Q2wfM/
Yet a third way is to use the slideToggle method of jQuery which allows for some effects. Such as $('#showMe').slideToggle('slow'); which will slowly display the hidden div.
Many problems here
I've set up a fiddle that works for you: http://jsfiddle.net/w9kSU/
$('.majorpointslegend').click(function(){
if($(this).text()=='Expand'){
$('#mylist').show();
$(this).text('Colapse');
}else{
$('#mylist').hide();
$(this).text('Expand');
}
});
try jquery,
<div>
<a href="#" class="majorpoints" onclick="majorpointsexpand(" + $('.majorpointslegend').html() + ")"/>
<legend class="majorpointslegend">Expand</legend>
<div id="data" style="display:none" >
<ul>
<li></li>
<li></li>
</ul>
</div>
</div>
function majorpointsexpand(expand)
{
if (expand == "Expand")
{
$('#data').css("display","inherit");
$(".majorpointslegend").html("Collapse");
}
else
{
$('#data').css("display","none");
$(".majorpointslegend").html("Expand");
}
}
Here there is my example of animation a staff list with expand a description.
<html>
<head>
<style>
.staff { margin:10px 0;}
.staff-block{ float: left; width:48%; padding-left: 10px; padding-bottom: 10px;}
.staff-title{ font-family: Verdana, Tahoma, Arial, Serif; background-color: #1162c5; color: white; padding:4px; border: solid 1px #2e3d7a; border-top-left-radius:3px; border-top-right-radius: 6px; font-weight: bold;}
.staff-name { font-family: Myriad Web Pro; font-size: 11pt; line-height:30px; padding: 0 10px;}
.staff-name:hover { background-color: silver !important; cursor: pointer;}
.staff-section { display:inline-block; padding-left: 10px;}
.staff-desc { font-family: Myriad Web Pro; height: 0px; padding: 3px; overflow:hidden; background-color:#def; display: block; border: solid 1px silver;}
.staff-desc p { text-align: justify; margin-top: 5px;}
.staff-desc img { margin: 5px 10px 5px 5px; float:left; height: 185px; }
</style>
</head>
<body>
<!-- START STAFF SECTION -->
<div class="staff">
<div class="staff-block">
<div class="staff-title">Staff</div>
<div class="staff-section">
<div class="staff-name">Maria Beavis</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Maria earned a Bachelor of Commerce degree from McGill University in 2006 with concentrations in Finance and International Business. She has completed her wealth Management Essentials course with the Canadian Securities Institute and has worked in the industry since 2007.</p>
</div>
<div class="staff-name">Diana Smitt</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Diana joined the Diana Smitt Group to help contribute to its ongoing commitment to provide superior investement advice and exceptional service. She has a Bachelor of Commerce degree from the John Molson School of Business with a major in Finance and has been continuing her education by completing courses.</p>
</div>
<div class="staff-name">Mike Ford</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Mike: A graduate of École des hautes études commerciales (HEC Montreal), Guillaume holds the Chartered Investment Management designation (CIM). After having been active in the financial services industry for 4 years at a leading competitor he joined the Mike Ford Group.</p>
</div>
</div>
</div>
<div class="staff-block">
<div class="staff-title">Technical Advisors</div>
<div class="staff-section">
<div class="staff-name">TA Elvira Bett</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Elvira has completed her wealth Management Essentials course with the Canadian Securities Institute and has worked in the industry since 2007. Laura works directly with Caroline Hild, aiding in revising client portfolios, maintaining investment objectives, and executing client trades.</p>
</div>
<div class="staff-name">TA Sonya Rosman</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Sonya has a Bachelor of Commerce degree from the John Molson School of Business with a major in Finance and has been continuing her education by completing courses through the Canadian Securities Institute. She recently completed her Wealth Management Essentials course and became an Investment Associate.</p>
</div>
<div class="staff-name">TA Tim Herson</div>
<div class="staff-desc">
<p><img src="http://www.craigmarlatt.com/canada/images/security&defence/coulombe.jpg" />Tim joined his father’s group in order to continue advising affluent families in Quebec. He is currently President of the Mike Ford Professionals Association and a member of various other organisations.</p>
</div>
</div>
</div>
</div>
<!-- STOP STAFF SECTION -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript"><!--
//<![CDATA[
$('.staff-name').hover(function() {
$(this).toggleClass('hover');
});
var lastItem;
$('.staff-name').click(function(currentItem) {
var currentItem = $(this);
if ($(this).next().height() == 0) {
$(lastItem).css({'font-weight':'normal'});
$(lastItem).next().animate({height: '0px'},400,'swing');
$(this).css({'font-weight':'bold'});
$(this).next().animate({height: '300px',opacity: 1},400,'swing');
} else {
$(this).css({'font-weight':'normal'});
$(this).next().animate({height: '0px',opacity: 1},400,'swing');
}
lastItem = $(this);
});
//]]>
--></script>
</body></html>
Fiddle
Take a look at toggle() jQuery function :
http://api.jquery.com/toggle/
Also, innerHTML jQuery Function is .html().
Since you have jQuery on the page, you can remove that onclick attribute and the majorpointsexpand function. Add the following script to the bottom of you page or, preferably, to an external .js file:
$(function(){
$('.majorpointslegend').click(function(){
$(this).next().toggle().text( $(this).is(':visible')?'Collapse':'Expand' );
});
});
This solutionshould work with your HTML as is but it isn't really a very robust answer. If you change your fieldset layout, it could break it. I'd suggest that you put a class attribute in that hidden div, like class="majorpointsdetail" and use this code instead:
$(function(){
$('.majorpoints').on('click', '.majorpointslegend', function(event){
$(event.currentTarget).find('.majorpointsdetail').toggle();
$(this).text( $(this).is(':visible')?'Collapse':'Expand' );
});
});
Obs: there's no closing </fieldset> tag in your question so I'm assuming the hidden div is inside the fieldset.
If you used the data-role collapsible e.g.
<div id="selector" data-role="collapsible" data-collapsed="true">
html......
</div>
then it will close the the expanded div
$("#selector").collapsible().collapsible("collapse");
Pure javascript allowing only one expanded div at a time. It allows multi-level sub-expanders. The html only need the expanders contents. The javascript will create the expanders headers with the titles form the content data attribute and a svg arrow.
<style>
/* expanders headers divs */
.expanderHead {
color: white;
background-color: #1E9D8B;
border: 2px solid #1E9D8B;
margin-top: 9px;
border-radius: 6px;
padding: 3px;
padding-left: 9px;
cursor: default;
font-family: Verdana;
font-size: 14px;
}
.expanderHead:first-child {
margin-top: 0 !important;
}
.expanderBody:last-child {
margin-bottom: 0 !important;
}
/* expanders svg arrows */
.expanderHead svg > g > path {
fill: none;
stroke: white;
stroke-width: 2;
stroke-miterlimit: 5;
pointer-events: stroke;
}
/* expanders contents divs */
.expanderBody {
border: 2px solid #1E9D8B;
border-top: 0;
background-color: white;
border-top-left-radius: 0;
border-top-right-radius: 0;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
padding: 6px;
font-family: Verdana;
font-size: 12px;
}
/* widget window */
.widget {
width: 400px;
background-color: white;
padding: 9px;
border: 2px solid #1E9D8B;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
border-bottom-left-radius: 6px;
border-bottom-right-radius: 6px;
}
</style>
<div class="widget">
<div data-title="expander 1" class="expanderBody">
expander 1 content
</div>
<div data-title="expander 2" class="expanderBody">
expander 2 content
</div>
<div data-title="expander 3" class="expanderBody">
<div>
expander 3 content
</div>
<div data-title="expander 3.1" class="expanderBody">
expander 3.1 content
</div>
<div data-title="expander 3.2" class="expanderBody">
expander 3.2 content
</div>
<div data-title="expander 3.3" class="expanderBody">
expander 3.3 content
</div>
</div>
</div>
<script>
document.querySelectorAll(".expanderBody").forEach(item => {
if (item.dataset.title) {
// create expander header
let divHeader = document.createElement("div");
divHeader.className = "expanderHead";
divHeader.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 5 5 L 10 1'/><path d='M 1 1 L 5 5'/></g></svg> <span>" + item.dataset.title + "</span>";
// expander click event
divHeader.addEventListener("click", function () {
// open / close expander
for (let i = 0; i < this.parentNode.children.length; i++) {
let expander = this.parentNode.children[i];
// check if it's expander header
if (expander.className == "expanderHead") {
if (expander == this && expander.nextElementSibling.style.display == "none") {
// open expander body
expander.nextElementSibling.style.display = "";
expander.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 1 5 L 5 1'/><path d='M 5 1 L 10 5'/></g></svg> <span>" + expander.nextElementSibling.dataset.title + "</span>";
expander.style.borderBottomLeftRadius = "0";
expander.style.borderBottomRightRadius = "0";
}
else {
// close expander body
expander.nextElementSibling.style.display = "none";
expander.innerHTML = "<svg width='14px' height='8px' viewBox='0 0 12 6'><g><path d='M 5 5 L 10 1'/><path d='M 1 1 L 5 5'/></g></svg> <span>" + expander.nextElementSibling.dataset.title + "</span>";
expander.style.borderBottomLeftRadius = "6px";
expander.style.borderBottomRightRadius = "6px";
}
}
}
}, true);
item.parentNode.insertBefore(divHeader, item);
item.style.display = "none";
}
});
</script>
Check out Jed Foster's Readmore.js library.
It's usage is as simple as:
$(document).ready(function() {
$('article').readmore({collapsedHeight: 100});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://fastcdn.org/Readmore.js/2.1.0/readmore.min.js" type="text/javascript"></script>
<article>
<p>From this distant vantage point, the Earth might not seem of any particular interest. But for us, it's different. Consider again that dot. That's here. That's home. That's us. On it everyone you love, everyone you know, everyone you ever heard of, every human being who ever was, lived out their lives. The aggregate of our joy and suffering, thousands of confident religions, ideologies, and economic doctrines, every hunter and forager, every hero and coward, every creator and destroyer of civilization, every king and peasant, every young couple in love, every mother and father, hopeful child, inventor and explorer, every teacher of morals, every corrupt politician, every "superstar," every "supreme leader," every saint and sinner in the history of our species lived there – on a mote of dust suspended in a sunbeam.</p>
<p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>
<p>Here's how it is: Earth got used up, so we terraformed a whole new galaxy of Earths, some rich and flush with the new technologies, some not so much. Central Planets, them was formed the Alliance, waged war to bring everyone under their rule; a few idiots tried to fight it, among them myself. I'm Malcolm Reynolds, captain of Serenity. Got a good crew: fighters, pilot, mechanic. We even picked up a preacher, and a bona fide companion. There's a doctor, too, took his genius sister out of some Alliance camp, so they're keeping a low profile. You got a job, we can do it, don't much care what it is.</p>
<p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>
</article>
Here are the available options to configure your widget:
{
speed: 100,
collapsedHeight: 200,
heightMargin: 16,
moreLink: 'Read More',
lessLink: 'Close',
embedCSS: true,
blockCSS: 'display: block; width: 100%;',
startOpen: false,
// callbacks
blockProcessed: function() {},
beforeToggle: function() {},
afterToggle: function() {}
},
Use can use it like:
$('article').readmore({
collapsedHeight: 100,
moreLink: 'Continue reading...',
});
I hope it helps.
Using Pure Javascript
const collapsableBtn = document.querySelectorAll('.collapsable-toggle');
for (let index = 0; index < collapsableBtn.length; index++) {
collapsableBtn[index].addEventListener('click', function(e) {
// e.preventDefault();
e.stopImmediatePropagation();
iterateElement = this;
getCollapsableParent = iterateElement.parentElement;
if(getCollapsableParent.classList.contains('show')) {
getCollapsableParent.classList.remove('show')
iterateElement.innerText = iterateElement.getAttribute('data-onCloseText');
} else {
getCollapsableParent.classList.add('show');
iterateElement.innerText = iterateElement.getAttribute('data-onOpenText');
}
})
}
.collapsable-container #expand {
display:none;
}
.collapsable-container.show #expand {
display:block;
}
<div class="collapsable-container">
Show First Content
<div id="expand">
This is some Content
</div>
</div>
<div class="collapsable-container">
Show Second Content
<div id="expand">
This is some Content
</div>
</div>

how to determine the element ID of div that is positioned x pixels to the right of visible screen?

Hitting a wall with this one, hope someone can lend a hand. I have a wrapper div containing many fixed-width "content" divs. It's like a table, except that the number of items "per row" aren't fixed, so that whenever the screen size is wide, more items fit onto the screen. Pretty basic.
Also, each of these "content" divs has an adjacent "details" div that is hidden by default ("style=display:none"), and an adjacent "separator" div that is empty, containing only the style "clear:both;".
Each content/details/separator div has a unique number in its ID, so that I can tell they are related (e.g., content123, details1234, separator1234)
Now, when one of these content divs is clicked, I want to reveal its "details" div below it. That part, I've got working partially, by wrapping an anchor tag around the content div, which fires an onClick javascript event, which in turns runs a jQuery statement to make visible the details and separator divs jQuery(".details1234").css("display","block");"
But you can imagine my problem. Once that "separator" div is reveled, it pushes down (clears) any "content" divs that appears to the right of it, ugly. My thought, what I have been wrestling with for hours, is to reveal the "separator" div of the content div, that is the last one appearing in the "row" that was clicked. That way, a new "row" will be opened up by the separator, so that when the "content" div is revealed it appears below the clicked item in the new row. To do that, I need to figure out the elementID of the last content div in the "row", and I was thinking about using the Y-coord of the mouse click event, plus the X-coord = to the right-most edge of the wrapper div minus half the width of the fixed-width content div. Something like that. But I am smashed into a wall and can't figure it out.
Can anyone help me do that? Or offer a different solution?
If sample code would help let me know, I could whip up an example, but it may take some screen space in this post.
Thanks everyone.. going nuts with this.
EDIT: the sample code below is based on my site. When a cell is clicked, you can see its "details" div appear below it, but unfortunately the other divs in the "row" get pushed down. that is the effect I'm trying to avoid. When a cell is clicked, I want the "details" to appear below it, but also the other divs to stay in their positions above the other cell's details, basically I want to keep the "row" intact. In the code, you can see my fruitless experiments using a "separator" div, because my assumption is that if I can insert that after the last div in the row, then the "details" div will become the next row, followed then by the next row of cells. Hope I explained it OK. Thanksgiving feast causing blood to divert from brain ;)
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style type="text/css">
#overallwrapper{
background: #CCCCCC;
padding-top: 4px;
padding-left: 4px;
padding-right: 4px;
padding-bottom: 4px;
margin-top: 5px;
}
.contentcell{
border: 2px solid blue;
padding: 4px;
float: left;
width: 200px;
}
.separator{
clear:both;
display: none;
}
.details{
background:lightgreen;
border: 2px solid green;
width:450px;
display:none;
float:left;
clear:both;
}
</style>
<script type="text/javascript">
function showDetails(contentid){
//first, reset all highlights and close any open content divs
$("#overallwrapper .contentcell").css("border","2px solid blue");
$(".details").css("display","none");
$(".separator").css("display","none");
//now highlight the clicked div and reveal its content div
var contentHI = "#content"+contentid;
var detailsON = "#details"+contentid;
var separatorON = "#separator"+contentid;
$(contentHI).css("border","2px solid green");
//$(separatorON).css("display","block");
$(detailsON).css("display","block");
}
</script>
</head>
<body>
<div id="overallwrapper">
<div id="contentwrapper01">
<div id="content01" class="contentcell">cell01</div>
<div id="details01" class="details">here are details about cell01</div>
<div id="separator01" class="separator"> </div>
</div>
<div id="contentwrapper02">
<div id="content02" class="contentcell">cell02</div>
<div id="details02" class="details">here are details about cell02</div>
<div id="separator02" class="separator"></div>
</div>
<div id="contentwrapper03">
<div id="content03" class="contentcell">cell03</div>
<div id="details03" class="details">here are details about cell03</div>
<div id="separator03" class="separator"></div>
</div>
<div id="contentwrapper04">
<div id="content04" class="contentcell">cell04</div>
<div id="details04" class="details">here are details about cell04</div>
<div id="separator04" class="separator"></div>
</div>
<div id="contentwrapper05">
<div id="content05" class="contentcell">cell05</div>
<div id="details05" class="details">here are details about cell05</div>
<div id="separator05" class="separator"></div>
</div>
<div id="contentwrapper06">
<div id="content06" class="contentcell">cell06</div>
<div id="details06" class="details">here are details about cell06</div>
<div id="separator06" class="separator"></div>
</div>
<div style="clear:both;"></div><!-- to prevent parent collapse -->
</div>
</body>
</html>
User ,
if you give as regular position be default , it pushes the other contents definetly down as they come in squence.
Change the hidden divs position to absolute so that it will go out of sequence and you can position at anywhere on the page by top and left property.
get the offset of the div you want next to...
http://api.jquery.com/offset/
it will have top and left property , use those property's and position next to them.
let me know if you need anything else.
give a bigger z-index for the hidden divs.
What about showing the details div with position: absolute, on top of everything else? (See here, the code's a little messy but you get the idea).
I partially figured it out, but the logic may be very clunky. I basically walk left by 100px from the width of the container div until I find a content div. Plus it doesn't work in IE8, because IE is not getting the same results from jQuery's offset() or position() as firefox, it always reports "19". So in IE, I can never get a Y-coordinate value. I'm too sleepy now to work on this anymore today. If someone can lend a hand or tell me how to improve the javascript that would be cool.
Here is the working code for Firefox (I changed javascript and css of the detail divs, compared to original question):
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style type="text/css">
#overallwrapper{
background: #CCCCCC;
padding-top: 4px;
padding-left: 4px;
padding-right: 4px;
padding-bottom: 4px;
margin-top: 5px;
}
.contentcell{
border: 2px solid blue;
padding: 4px;
float: left;
width: 200px;
}
.separator{
clear:both;
display: none;
}
.details{
background:lightgreen;
border: 2px solid green;
display:none;
clear:both;
}
</style>
<script type="text/javascript">
function showDetails(contentid){
//first, reset all highlights and close any open content divs
$("#overallwrapper .contentcell").css("border","2px solid blue");
$(".details").css("display","none");
$(".separator").css("display","none");
//now highlight the clicked div and reveal its content div
//first, figure out which separator to display.
//1.get the y-pos from the clicked element, this gives y-coord of the row
contentClicked = "#content"+contentid;
var clickedoffset = $(contentClicked).offset();
var ypos = clickedoffset.top;
var wrapperwidth = $("#overallwrapper").width();
for (var xpos=wrapperwidth; xpos>0; xpos-=100){
var elematpos = document.elementFromPoint(xpos, ypos);
var elematposid = elematpos.id;
if (elematposid.substring(0,7) == "content") {
var lastcontentdivID = elematposid.substring(7);
break;
}
}
$(contentClicked).css("border","2px solid green");
var detailsON = "#details"+contentid;
$(detailsON).css("display","block");
var lastidonscreen = "#content"+lastcontentdivID;
$(detailsON).insertAfter(lastidonscreen);
}
</script>
</head>
<body>
<div id="overallwrapper">
<div id="contentwrapper01">
<div id="content01" class="contentcell">cell01</div>
<div id="separator01" class="separator"> </div>
<div id="details01" class="details">here are details about cell01</div>
</div>
<div id="contentwrapper02">
<div id="content02" class="contentcell">cell02</div>
<div id="separator02" class="separator"></div>
<div id="details02" class="details">here are details about cell02</div>
</div>
<div id="contentwrapper03">
<div id="content03" class="contentcell">cell03</div>
<div id="separator03" class="separator"></div>
<div id="details03" class="details">here are details about cell03</div>
</div>
<div id="contentwrapper04">
<div id="content04" class="contentcell">cell04</div>
<div id="separator04" class="separator"></div>
<div id="details04" class="details">here are details about cell04</div>
</div>
<div id="contentwrapper05">
<div id="content05" class="contentcell">cell05</div>
<div id="separator05" class="separator"></div>
<div id="details05" class="details">here are details about cell05</div>
</div>
<div id="contentwrapper06">
<div id="content06" class="contentcell">cell06</div>
<div id="separator06" class="separator"></div>
<div id="details06" class="details">here are details about cell06</div>
</div>
<div style="clear:both;"></div><!-- to prevent parent collapse -->
</div>
</body>
</html>
EDIT:
Blasted IE. I just can't trust it to determine screen coordinates. I got it working though, but only for Firefox. again IE is trying to drive me insane by not handling insertAfter properly. arrgh! here is the final code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style type="text/css">
#overallwrapper{
background: #CCCCCC;
padding-top: 4px;
padding-left: 4px;
padding-right: 4px;
padding-bottom: 4px;
margin-top: 5px;
}
.contentwrapper{
}
.contentcell{
padding: 4px;
float: left;
width: 200px;
height: 100px;
border: 2px solid blue;
}
.separator{
clear:both;
display: none;
}
.details{
background:lightgreen;
border: 2px solid green;
display:none;
clear:both;
}
</style>
<script type="text/javascript">
function showDetails(contentid){
//first, reset all highlights and close any open content divs
$("#overallwrapper .contentcell").css("border","2px solid blue");
$(".details").css("display","none");
$(".separator").css("display","none");
var contentClicked = "#content"+contentid;
var thisypos = $(contentClicked).offset().top;
var nextdivid = contentClicked;
var countid = contentid;
do
{
var prevdivid = nextdivid;
var nextcontentid = (countid * 1) + 1;
var nextcontentid = '' + nextcontentid;
if ( nextcontentid.length < 2)
{ nextcontentid = "0" + nextcontentid; }
nextdivid = "#content" + nextcontentid;
if ( $(nextdivid).length ) {
var nextypos = $(nextdivid).offset().top;
countid++;
} else {
break;
}
}
while (thisypos == nextypos);
$(contentClicked).css("border","2px solid green");
var detailsON = "#details"+contentid;
$(detailsON).css("display","block");
$(detailsON).insertAfter(prevdivid);
}
</script>
</head>
<body>
<div id="overallwrapper">
<div id="contentwrapper01" class="contentwrapper">
<div id="content01" class="contentcell">cell01</div>
<div id="separator01" class="separator"> </div>
<div id="details01" class="details">here are details about cell01</div>
</div>
<div id="contentwrapper02" class="contentwrapper">
<div id="content02" class="contentcell">cell02</div>
<div id="separator02" class="separator"></div>
<div id="details02" class="details">here are details about cell02</div>
</div>
<div id="contentwrapper03" class="contentwrapper">
<div id="content03" class="contentcell">cell03</div>
<div id="separator03" class="separator"></div>
<div id="details03" class="details">here are details about cell03</div>
</div>
<div id="contentwrapper04" class="contentwrapper">
<div id="content04" class="contentcell">cell04</div>
<div id="separator04" class="separator"></div>
<div id="details04" class="details">here are details about cell04</div>
</div>
<div id="contentwrapper05" class="contentwrapper">
<div id="content05" class="contentcell">cell05</div>
<div id="separator05" class="separator"></div>
<div id="details05" class="details">here are details about cell05</div>
</div>
<div id="contentwrapper06" class="contentwrapper">
<div id="content06" class="contentcell">cell06</div>
<div id="separator06" class="separator"></div>
<div id="details06" class="details">here are details about cell06</div>
</div>
<div style="clear:both;"></div><!-- to prevent parent collapse -->
</div>
</body>
</html>

Categories

Resources