I tried something with div tag as follows,
<style type="text/css">
#hello{
visibility: visible;
cursor: pointer;
position: absolute;
}
#list{
visibility: hidden;
cursor: pointer;
position: absolute;
top: 30px;
z-index: 1;
background-color: aqua;
}
#second{
position: absolute;
}
</style>
<div id="hello" onclick="{if(list.style.visibility=='hidden'){list.style.visibility='visible';}else{list.style.visibility='hidden'};}">Hello user</div><br/>
<div id="second">Welcome to smartdata</div>
<div id="list">
Home <br/>
SignOut <br/>
</div>
It is working fine but the problem is list is not displaying on the first click. Any thing wrong with my code.??
Your code doesn't work as you expect it to due to the way element.style works.
Check this MDN link on element.style: https://developer.mozilla.org/en/DOM/element.style
Since the style property has the same (and highest) priority in the
CSS cascade as an inline style declaration via the style attribute, it
is useful for setting style on one specific element.
However, it is not useful for learning about the element's style in
general, since it represents only the CSS declarations set in the
element's inline style attribute, not those that come from style
rules elsewhere, such as style rules in the section, or
external style sheets.
So when you first run your code and even if your element.style.hidden is declared in the external CSS sheet, the style declaration remains empty and you need to perform additional checks.
if (!list.style.visibility || list.style.visibility === 'hidden') {...}
You can take a look at the fiddle to see it work: http://jsfiddle.net/Kk6TJ/1/
Also:
It's best to use triple equal === to perform strict comparison without converting variable type.
You don't need curly braces in your event handlers. If you were hoping that they would create scope - they don't! Only functions in JavaScript have scope.
list.style.visibility=='hidden' is a false statement on first click
try this
{if(list.style.visibility=='hidden' || list.style.visibility='')
<style type="text/css">
#hello{
visibility: visible;
cursor: pointer;
position: absolute;
}
#list{
visibility: hidden;
cursor: pointer;
position: absolute;
top: 30px;
z-index: 1;
background-color: aqua;
}
#second{
position: absolute;
}
</style>
<div id="hello" onclick="{if(list.style.visibility=='hidden' || list.style.visibility==''){list.style.visibility='visible';}else{list.style.visibility='hidden'};}">Hello user</div><br/>
<div id="second">Welcome to smartdata</div>
<div id="list">
Home <br/>
SignOut <br/>
</div>
This is because your if..else are not in order. Re-ordering of decision statement corrected the behavior, Now first click is showing the menu items.
Also, If you run your script and watch it in firebug console you'll see your javascript code is throwing warning on first click.
I've updated your code -
<style type="text/css">
#hello{
visibility: visible;
cursor: pointer;
position: absolute;
}
#list{
visibility: hidden;
cursor: pointer;
position: absolute;
top: 30px;
z-index: 1;
background-color: aqua;
}
#second{
position: absolute;
}
</style>
<script type="text/javascript">
function Clickme()
{
var list = document.getElementById('list');
if(list.style.visibility=='visible')
{
list.style.visibility='hidden';
}
else
{
list.style.visibility='visible'
}
}
</script>
<div id="hello" onclick="Clickme();">Hello user</div><br/>
<div id="second">Welcome to smartdata</div>
<div id="list">
Home <br/>
SignOut <br/>
</div>
Styles defined in style tags and css files are not in the element.style.property property, they are available if the element has its style set inline <element style="property:value;"> or explicitly element.style.property = value;
To get styles for an element defined in style tags/sheets use window.getComputedStyle(element, null).getPropertyValue(property);`
So you can either inline the styles on list, use getComputedStyle getPropertyValue or use the fact that list.style.visibility is going to be empty on the first click.
Go for something like this -
if(list.style.visibility=="visible")
{
list.style.visibility="hidden";
}
else
{
list.style.visibility="visible"
}
Related
I would like to make a check box which if checked the button enables. If the checkbox is unchecked the button should be disabled.
Could someone help me with this? I think I'm very close just missing a way to connect these lines.
Thanks in advance!
<button disabled="Calendly.initPopupWidget({url: 'https://calendly.com/xxxxxxxxxxx'});return false;">Plan</button>
<td width="10px" style="min-width: 10px"></td>
<td width="70%">
<input type="checkbox" name="TOS" value="Accept" onClick="button enabled"> I agree to Terms of Service agreement.
</td>
You can work on something like this.
const checkbox = document.getElementById('myCheckbox')
const planbtn = document.getElementById('planBtn')
checkbox.addEventListener('change', (event) => {
if (event.currentTarget.checked) {
planbtn.disabled = false;
} else {
planbtn.disabled = true;
}
})
<button id="planBtn" disabled="Calendly.initPopupWidget({url: 'https://calendly.com/xxxxxxxxxxx'});return false;">Plan</button>
<td width="10px" style="min-width: 10px"></td>
<td width="70%">
<input type="checkbox" name="TOS" value="Accept" id="myCheckbox"> I agree to Terms of Service agreement.
</td>
So, what you want to do is the following:
document.getElementById('TOS').onclick = function() {
if (this.checked) {
document.getElementById('plan').disabled = false;
} else {
document.getElementById('plan').disabled = true;
}
}
<button disabled="Calendly.initPopupWidget({url: 'https://calendly.com/xxxxxxxxxxx'});return false;" id="plan">Plan</button>
<!-- id="plan" has been added for reference in JS -->
<td width="10px" style="min-width: 10px"></td>
<td width="70%">
<input id="TOS" type="checkbox" name="TOS" value="Accept" onClick="button enabled"> I agree to Terms of Service agreement.
<!-- id="TOS" has been added for reference in JS -->
</td>
All this does, is when the checkbox input has been clicked, the code checks to see if it is checked. If so, it sets disabled to false for the button. Otherwise, the disabled property of the button is true.
Yet another variation that's essentially the same as the others:
const btn = document.querySelector("button");
const chk = document.querySelector("input[type='checkbox']");
chk.addEventListener("click", () => { handleClick(btn); });
function handleClick(btn) {
btn.disabled = !btn.disabled;
}
It finds the button element, finds your checkbox, and then listens for a click. It toggles the button's disabled attribute with that click.
HTML & CSS Solution
Do the following:
HTML
Markup
Move checkbox before the button.
Remove the <td> if it isn't in a <tr> inside a <table> then it's invalid HTML. If you are using a table as layout and not for data then it's not sementic.
Add a <label> after the button.
Attributes
The values do not have to be exactly what is in the examples. They are specific to avoid any confusion and some will be reused specifically in another property.
Add the following to checkbox:
id="TOS"
Add the following to button:
class="cal" See CSS
type="button" Just in case the button is inside a <form>
Remove the disabled attribute from button. Note the only value assigned to disabled is a Boolean: true or false.
Remove the JavaScript from button. Keep presentation (CSS), structure (HTML), and content (JavaScript) separate from each other as much as possible. The correct way isn't disabled="...." it's onclick="...". That onclick="..." is called an inline event attribute or inline event handler, but avoid using them as well because inline event handlers are garbage. The proper way is to either write the JavaScript on a external file or in a <script> block, the latter is demonstrated in the example below.
Add the following to the <label>:
for="TOS" This will associate <label> with the checkbox. Now as long as they are both on the same page (no matter how far apart they are), clicking one will also click the other.
class="chx" See CSS.
CSS
There is some extensive CSS in the example so only the important aspects will be discussed. What isn't mentioned is for aesthetics.
Checkbox
The styles assigned to #TOS is just to hide it visually but not from screenreaders, if you're not concerned about sight impaired users then display: none is sufficient:
#TOS {
position: absolute;
clip: rect(0 0 0 0); clip-path: inset(50%);
width: 1px; height: 1px;
overflow: hidden; white-space: nowrap;
}
Note: The whole purpose of relocating and hiding the checkbox is because CSS operates in a casscading pattern, which requires that selectors that have an alternate state (ex. checked/unchecked) can dictate the styles of oyher selectors that are either within or after (under) of that that selector in the HTML layout. The next styles demonstrate this relationship between checkbox (input#TOS) and button (button.cal) and checkbox (input#TOS) and label (label.chx).
Button
In default state, .cal is disabled (do not confuse it's state with disabled attribute, it will not be used because JavaScript is needed to change it.):
.cal {
pointer-events: none; /* Can't click on it */
color: white; background: lightgrey;
outline: none; /* Can't focus on it */
}
When the checkbox is checked, .cal is enabled, the + is an adjacent sibling combinator which specifies that whatever follows afterwards is the selector assigned the styles:
#TOS:checked+.cal {
pointer-events: auto; /* Can click it */
color: black; background: white;
outline: initial; /* Can focus on it */
cursor: pointer;
}
Label
Also, when the checkbox is checked the label changes as well. The label is now the only way the hidden checkbox can be checked/unchecked because the label has for="TOS" which links them together. The label has two pseudo-elements ::before and ::after. ::after has the text next to the fake checkbox. ::before consists of two Unicode characters which serves as a substitute for the hidden checkbox. The ~ is a general sibling combinator which works like the adjacent sibling combinator but instead of stopping at the selector right afterwards, it continues to find all selectors thereafter:
.chx::before {
content: '\002b1b'; /* ⬛ a large black square as default */
...
}
/* When checkbox is checked label.chx changes it's fake checkbox */
#TOS:checked~.chx::before {
content: '\002611\00fe0f'; /* ☑️ a checkbox check */
}
Example
/* This is a proper onevent property -
if button.cal is clicked the anonymous function will be invoked.
*/
document.querySelector('.cal').onclick = function(e) {
Calendly.initPopupWidget({
url: 'https://calendly.com/xxxxx'
});
};
*,
*::before,
*::after {
box-sizing: border-box;
}
:root {
font: 1ch/1.25 'Segoe UI';
}
html,
body {
width: 100%;
min-height: 100%;
}
body {
display: flex;
justify-content: space-around;
align-items: flex-start;
font-size: 2rem;
}
#TOS {
position: absolute;
clip: rect(0 0 0 0);
clip-path: inset(50%);
width: 1px;
height: 1px;
overflow: hidden;
white-space: nowrap;
}
button {
display: block;
width: max-content;
margin: 0 4px;
padding: 2px 4px;
border-radius: 4px;
font-size: 100%;
}
label {
display: inline-table;
margin: 0 4px;
}
.chx::before {
content: '\002b1b';
display: table-cell;
font-size: 2rem;
padding: 0 4px;
}
.chx::after {
content: ' I agree to Terms of Service agreement.';
display: table-cell;
padding: 0 4px;
}
.cal {
pointer-events: none;
color: white;
background: lightgrey;
outline: none;
}
#TOS:checked~.chx::before {
content: '\002611\00fe0f';
}
#TOS:checked+.cal {
pointer-events: auto;
color: black;
background: white;
outline: initial;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Calendy Widget</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href='https://fake.com/path/to/style.css' rel='stylesheet'>
<style>
/* This is where CSS goes */
</style>
</head>
<body>
<input id='TOS' name="TOS" type="checkbox" value="Accept">
<button class='cal' type='button'>Plan</button>
<label for="TOS" class='chx'></label>
<script src='https://fake.com/path/to/script.js'></script>
<script>
/* This is where JavaScript goes */
</script>
</body>
</html>
I've created a vertical navigation on the left of our site. We'd like the background color for a .item to change based on the subdirectory where a user is viewing content. So if someone clicks on a nav .item, the href will redirect them to a page and we want that .item to be highlighted a unique hex color that we can customize for each nav .item. All 6 nav items would have a different color.
One point of clarification is that sometimes folks may visit our site without having ever clicked a navigation item. I want the navigation items to still be highlighted based on the current subdirectory where a person is viewing content. This helps them easily identify where they are and how to get back if they navigate to other parts of the community. Also if a person does a global search and stumbles upon content in one of our 6 main areas, we want the nav menu to instantly identify their current location (based on url) and highlight that nav .item in our vertical nav bar.
Is Javascript or Jquery the way to go? Any help would be appreciated!!
Heres a FIDDLE with all the code.
sample CSS:
.navback {
position: fixed;
top: 0;
left: 0px;
width: 100px;
height: 100%;
background: #283237;
z-index: 4;
}
.navbar {
position: fixed;
top: 44px;
left: 0px;
width: 100px;
height: 60vh;
background: #283237;
display: flex;
z-index: 5;
flex-direction: column;
}
.topbar {
border-top: 1px solid #000;
top: 44px;
}
.navbar .item {
flex: 1;
text-align: center;
display: flex;
justify-content: center;
flex-direction: column;
padding-top: 40px;
padding-bottom: 40px;
max-height: 100px;
z-index: 5;
}
.navbar .item div.label {
color: #fff;
position: relative;
top: 5px;
font-size: 13px;
font-family: -apple-system, BlinkMacSystemFont, Helvetica, Arial, "Segoe UI", sans-serif;
transition: all 300ms cubic-bezier(0.68, -0.55, 0.27, 1.55);
left: -100px;
}
Sample HTML:
<div class="topbar"></div>
<div class="navback leftnav">
<div class="navbar">
<div class="item hvr-shrink">
<a href="https://community.canopytax.com/">
<div>
<img src="https://png.icons8.com/ios/35/ffffff/home.png"/>
<div class="label">Home</div>
</div>
</a>
</div>
<div class="item hvr-shrink">
<a href="https://community.canopytax.com/community-central/">
<div>
<img src="https://png.icons8.com/ios/40/ffffff/conference-call.png">
<div class="label">Central</div>
</div>
</a>
</div>
JS/jQuery
// get the first directory by splitting "/dir/path/name" into an array on '/'
// get [1] instead of [0] b/c the first should be blank. wrap in /s.
hereDir = "/" + window.location.pathname.split("/")[1] + "/";
// rebuild the URL since you're using absolute URLs (otherwise just use hereDir)
hereUrl = window.location.protocol + "//" + window.location.host + hereDir;
$(".item")
.find("[href^='" + hereUrl + "']")
.closest(".item").addClass("here");
Note .find("[href^=...]") selects things that start with what you're looking for.
CSS
/* now use .here to style */
.item.here {
background-color: purple;
}
.item.here .label {
font-weight: bold;
}
To answer your question directly, yes this could be done also via JavaScript/jQuery but there is a far simpler way using the css :active selector.
For example, if the user clicks the .item
then the code would be:
.item:active {
background-color: #cecece; // or whatever styling you want
}
Sidenote: As a webdesigner myself, in general i'd advise using the :hover selector when it comes to navbar highlightng instead of the :active one.
Use jquery in your html (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js)
Add the following script
$('.item').click(function(){
$('.item.active').removeClass("active");
$(this).addClass('active');
})
CSS
.item.active {
background-color: red;
}
Please see updated fiddle
If you are using jQuery you can loop through each anchor and test it against the current URL of the page like this:
$(function highlightCurrentUrl() {
var currentUrl = window.location.href;
var items = $(".item").each(function() {
var anchor = $(this).find('a');
$(this).removeClass('active');
//comparison logic
if (anchor.prop('href') == currentUrl) {
$(this).addClass("active");
}
});
});
What this does is add a class to the matching .item in the menu. (This won't work in JSFiddle due to Content Security policy so you will have to test it your own environment.)
Next, you will need to define the styles that will be applied to an .item.active DIV tag. And, if you want different colors for different items, you should probably give them ID's in you markup, so you can reference them individually:
<div class="item hvr-shrink" id="home-link">
<a href="https://community.canopytax.com/">
<div>
<img src="https://png.icons8.com/ios/35/ffffff/home.png"/>
<div class="label">Home</div>
</div>
</a>
</div>
<div class="item hvr-shrink" id="central-link">
<a href="https://community.canopytax.com/community-central/">
<div>
<img src="https://png.icons8.com/ios/40/ffffff/conference-call.png">
<div class="label">Central</div>
</div>
</a>
</div>
These rules are saying that when the active class is added to the div with the ID home-link or central-link it should have the following properties
#home-link.active {
background-color: blue;
}
#central-link.active {
background-color: green;
}
I have the following html:
<div class="mydiv">
<p>some text here</p>
<input type='text' />
</div>
...with the following CSS:
.mydiv {
background-color:yellow;
}
.mydiv:focus, .mydiv:hover {
background-color:orange;
}
The :hover is changing the background color appropriately, but the :focus is not having any effect. Is this because the <div> cannot truly have focus?
Is there a CSS solution to make .mydiv change background color when any of its children receive focus?
Here's a fiddle.
There is no CSS solution for this. But, you can achieve this by using jQuery.
$(".mydiv").children().focus(function() {
$(this).parent().css("background-color", "orange");
}).blur(function() {
$(this).parent().css("background-color","yellow");
});
Here is the Fiddle
You have to add the tabindex attribute to the element needs to be focusable.
Here is the Fiddle
But, to answer your question, there is no pure CSS solution to make the div bg color change if its children receive focus.
When using jQuery, I think you're better off using the focusin and focusout events.
The code as adapted from the accepted answer would then become:
$(".mydiv").focusin(function() {
$(this).css("background-color", "orange");
}).focusout(function() {
$(this).css("background-color","yellow");
});
though, personally, I'd rather use a "focus" class:
$(".mydiv").focusin(function() {
$(this).addClass("focus");
}).focusout(function() {
$(this).removeClass("focus");
});
combined with the css for the combined selector:
.mydiv.focus { background-color: orange }
p.s. For once, I find the bit of docs on w3schools more informative than the demo on api.jquery.com, which just looks confusing to me.
Possible CSS solution:
<style>
#row1 {display: block; position: relative; width: 100%; background-color: #ffffff; z-index: 150;}
.BGmagic {display: none; position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; background-color: #efefef; z-index: 200;}
#inputone{display: block; position: relative; z-index: 250;}
#inputone:focus + .BGmagic {display: block;}
#inputone:hover + .BGmagic {display: block;}
</style>
<form>
<div ID="row1">
<p style="position: relative; z-index: 250;">First name:</p>
<input ID="inputone" type="text" name="firstname">
<div class="BGmagic"></div>
</div>
</form>
When you click a link, a:active style of the clicked link is being applied. So when I've got a link which gets called and activated from the url using its name like whats shown below, why doesn't my code work?
.box{
display:block;
width:100px;
height:100px;
background:gray;
margin:20px 0px;
}
a{
-moz-transition:all 1s ease;
-webkit-transition:all 1s ease;
}
a:active{
background:orange;
}
<body>
user
<a class="box" name="user">userbox</a>
</body>
I want it to call a:active css for userbox when userbox is called from the url.
Is my code invalid or not an option for these kind of situations?
I think the pseudo-class you want is :focus. :active is applied while a link is being clicked.
-EDIT-
Of the browsers I tested, only Internet Explorer 11 focused the anchor when the URL was updated to include #user. You can use JavaScript to set a class as follows:
window.addEventListener('hashchange', function () {
var activeElement = document.getElementById(window.location.hash.substring(1));
if (activeElement) {
activeElement.className = 'active';
}
});
This would require using the following CSS:
.active {
color: orange;
}
And this assumes using id="user" instead of name="user" which both behave the same with regard to the URL hash.
I want it to call a:active css for userbox when userbox is called from the url. my code is invalid or it's not an option for this kinda situations?
You can't. :active means "While being clicked on or otherwise activated". It does not mean "Having an href attribute that resolves to the current URI".
Use some other mechanism, such as adding a class to the element in the HTML.
We can hack it, we have the technology.
In all seriousness you should use classes and Javascript for this solution, but I put a bit too much of my lunch time into this to just throw it away.
http://jsfiddle.net/DF4VG/
CSS:
#label {
display: block;
}
#label:hover {
cursor: pointer;
text-decoration: underline;
}
#container {
position: relative;
}
#wrapper {
z-index: 2;
position: relative;
}
#user {
border: none;
background: transparent;
position: absolute;
top: 0;
bottom: 0;
width: 100%;
z-index: 1;
transition: all 1s ease;
}
#user:focus {
background: orange;
}
HTML:
<form action="">
<label id="label" for="user">User</label>
<div id="container">
<div id="wrapper">
<p>There is some content in here</p>
<p>And some more</p>
<p>And so forth</p>
</div>
<input type="text" id="user" value="" readonly>
</div>
</form>
I am setting up a FAQ page. On the page I have a div, of class=”faq_container”, with 6 child divs arranged in a 3×3 grid that contain the faq questions. So basically I have 6 clickable boxes.
Each question, when clicked, will reveal its answer hiding the all the questions but maintained within the faq_container div. There would be a close link below the answer to hide the answer and take you back to the questions.
I know this is probably pretty simple. I’m hoping someone can help me out.
Thanks!
While you've accepted a JavaScript solution, there are (at least) two ways that this can be achieved with CSS alone, the first using CSS :target pseudo-classes, and the second using input, and label, elements.
The first, assuming HTML similar to the following:
<div id="faq_container">
<ol>
<li id="faq1">
<h2>Question 1</h2>
<div>
<p>Text, relating to question one.</p> <a class="close" href="#hide">close</a>
<!-- the above link doesn't link to anything, just changes the hash whcih stops the ':target' pseudo-class matching the the current 'div' element -->
</div>
</li>
<!-- subsequent elements follow the above structure, stripped for brevity -->
</ol>
</div>
With the following CSS (albeit there's more CSS in the demo, since I've stripped out some of the purely aesthetic stuff here, for brevity, as above):
li {
/* some stripped out aesthetics */
position: relative; /* used to position the '.close' links */
}
li div {
height: 0; /* to allow for animation of the height 'none' to 'block' can't animate */
overflow: hidden;
/* all vendor prefixes removed for brevity, here and later */
transition: all 0.5s linear; /* animates to the default properties, from other 'states' */
}
/* li:target matches when the 'id' of the 'li' is equal to the hash/fragment-identifier in the URL */
li:target div {
height: 4em; /* to allow for animation (this is the awkward part of using pure CSS) */
transition: all 0.5s linear; /* transitions to the 'selected' state (when the user clicks a link in the 'h2' element) */
}
li a:link, li a:visited {
/* aesthetics removed */
}
/* styling the 'interactive' states (:hover, :active, :focus), and the 'selected' state using 'li:target h2 a' */
li a:hover, li a:active, li a:focus, li:target h2 a {
font-weight: bold;
text-decoration: underline;
}
a.close {
/* styling the '.close' link, so it's invisible in the 'non-selected' state */
position: absolute;
opacity: 0;
width: 0;
overflow: hidden;
transition: all 0.65s linear;
}
/* styling the '.close' link, so it's only visible when the question is 'selected' */
li:target a.close {
opacity: 1;
width: 4em;
transition: all 0.65s linear;
}
JS Fiddle demo.
The second approach uses label and input elements (type="radio" if only one question can be visible at a time, type="checkbox" if multiple elements can be visible), based on the following HTML:
<input id="close" name="question" type="radio" />
<div id="faq_container">
<ol>
<li>
<input id="faq1" type="radio" name="question" />
<h2><label for="faq1">Question 1</label></h2>
<div>
<div>
<p>Text, relating to question one.</p>
<label for="close">Close</label>
<!-- the above 'label' closes the question, by referring to an
'input' of the same name (different 'id'), taking advantage
of the fact that only one radio-'input' of a given name can
be checked (this 'input' is just before the ancestor 'ol') -->
</div>
</div>
</li>
<!-- subsequent elements follow the above structure, stripped for brevity -->
</ol>
</div>
And the following CSS (as before, aesthetics removed for brevity):
/* you could, instead, use a class-name to identify the relevant radio-inputs */
input[type=radio] {
/* using 'display: none' (apparently) in some browsers prevents
interactivity, so we fake it, by hiding: */
position: absolute;
opacity: 0;
left: -1000px;
}
/* styling the 'div' that's the adjacent-sibling of an 'h2' which is an
adjacent-sibling of an 'input' all of which are descendants of a 'div' */
div input + h2 + div {
height: 0; /* to allow for animating with transitions */
overflow: hidden;
/* vendor prefixes, again, stripped out */
transition: all 0.5s linear;
}
/* using 'input:checked + h2 + div' causes problems in Chrome, check the references;
so we're styling (respectively) a 'div' which is an adjacent sibling to an 'h2'
which is an adjacent-sibling of a checked 'input', and/or
a 'div' which is a general-sibling of a checked 'input' (in both cases these are
all descendants of another 'div' element) */
div input:checked + h2 + div,
div input:checked ~ div {
height: 4em; /* to allow for animating with transitions */
overflow-y: auto; /* a personal preference, but allows for
scrolling if the height is insufficient
though it can be a little ugly, with a flicker */
transition: all 0.5s linear;
}
JS Fiddle demo.
The same approach can be used with checkboxes, which allows the label to toggle the display of the relevant question, and makes the close links/labels pointless, HTML:
<div id="faq_container">
<ol>
<li>
<input id="faq1" type="checkbox" name="question" />
<h2><label for="faq1">Question 1</label></h2>
<div>
<div>
<p>Text, relating to question one.</p>
</div>
</div>
</li>
<!-- subsequent elements follow the above structure, stripped for brevity -->
</ol>
</div>
And CSS (precisely as the preceding example, but changed input[type=radio] to input[type=checkbox]):
/* duplicated, and aesthetic, CSS removed for brevity */
input[type=checkbox] {
position: absolute;
opacity: 0;
left: -1000px;
}
JS Fiddle demo.
References:
:target pseudo-selector.
Adjacent-sibling (+) combinator.
General-sibling (~) combinator.
Problems using chained adjacent-sibling combinators, particularly in Chrome: "Why does the general-sibling combinator allow toggling pseudo-element's content, but not the adjacent-sibling?"
If a jQuery solution is allowed, here is a quick mock-up.
$(".wrapper").click(function(){
$(this).children(".answer").toggle();
$(".wrapper").not(this).toggle();
$(".faq_container").toggleClass("active");
});
The simplest means of achieving what you're asking for comes down to changing the "class" attribute value of these DIV elements when their respective OnClick events are fired. For that, you'll need to use a scripting engine of some kind, and that is likely going to be JavaScript unless you want a post back, in which case you can just handle it in the code behind of the page. JQuery, as others have mentioned, is a good choice, but comes with some overhead.
The way this site works is that you post what you've tried so far, and what results you're getting. I get the impression that you haven't tried anything, so I would suggest that you do some searching on this site or your web search engine of choice for a string like "javascript change css class onclick" and see where that leads you.
Without more specifics on your exact use case and environment, you are unlikely to get a "here, copy and paste this code into your page" type of answer.
[EDIT] Never mind. I always underestimate the compulsion of developers to begin writing code before knowing any constraints. Enjoy your copypasta.
You should use this kind of structure :
$('.question').on('click', function(ev) {
ev.preventDefault();
$(this).find('.answer').show();
});
$('.close').on('click', function(ev) {
ev.preventDefault();
ev.stopPropagation();
var dismiss = $(this).data('dismiss');
$(this).closest('.'+dismiss).hide();
});
.faq {
position: relative;
width: 600px;
}
.question {
height: 178px; width: 178px;
margin: 5px;
padding: 5px;
border: 1px solid black;
background: #efefef;
float: left;
cursor: pointer;
}
.answer {
position: absolute;
top: 0; left: 0;
height: 578px; width: 578px;
margin: 5px;
padding: 5px;
border: 1px solid black;
background: #bebebe;
cursor: default;
display: none;
}
a.close {
position: absolute;
top: 5px; right: 5px;
display: block;
height: 20px; width: 20px;
color: black;
border: 1px solid black;
line-height: 20px;
text-align: center;
text-decoration: none;
}
a.close:hover {
background: #9f9f9f;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<section class="faq">
<article class="question">Question 1 ?
<div class="answer">
Answer 1 !
×
</div>
</article>
<article class="question">Question 2 ?
<div class="answer">
Answer 2 !
×
</div>
</article>
<article class="question">Question 3 ?
<div class="answer">
Answer 3 !
×
</div>
</article>
<article class="question">Question 4 ?
<div class="answer">
Answer 4 !
×
</div>
</article>
<article class="question">Question 5 ?
<div class="answer">
Answer 5 !
×
</div>
</article>
<article class="question">Question 6 ?
<div class="answer">
Answer 6 !
×
</div>
</article>
<article class="question">Question 7 ?
<div class="answer">
Answer 7 !
×
</div>
</article>
<article class="question">Question 8 ?
<div class="answer">
Answer 8 !
×
</div>
</article>
<article class="question">Question 9 ?
<div class="answer">
Answer 9 !
×
</div>
</article>
</section>
For the CSS, you'll need to mix float: left for your 3*3 pattern, and position: absolute for each answer.