I hava a large amount of content which make up with html tag or pure text.
And I have several divs.
How to autofill the remain content to other divs when the first div cannot contain all contents.
Very thankful if any suggestion provided. :)
--- Update ---
Actually, I'm making my own blog which designed like an opened book(a left page and a right page) containing all posts.
Each post is written with a markdown file.Initially, one post has only a left page.
When the mardown file parsed to html code, I will try insert the result html code into 'left page' of my book-like post.
Obviously, If the result html code is huge, one 'left page' is not possible contain all content.On this occasion, my blog will automatically create a new 'right page'(or another 'left page' when the 'right page' is neither enough) which the remain content should autofilled in;
What I'm asking is how I can detect if my 'left page' div is not enough containing the all result html code.And how can I cut the remain content and insert into 'right page'.I totally have no idea how to reach this request.
So, If someone already did this before, maybe you can give me some tips.I'll be very thankful
EDITED again:
Ok I will make this out of pure CSS. What you are asking me in the comments is a normal post(on the left side) and if the left sided post is unable to hold all of its content then a copy of the post is revealed on the right side that can hold all of the original content of the old left side.
This is what I am understanding from the information you have given me.
#media (min-width: 601px) {
#leftSide {
float: left;
}
/*THIS IS ON THE LEFT SIDE*/
h2 {
font-size: 2.5em;
}
p {
font-size: 1.5em;
}
#rightSide {
display: none;
}
}
#media (max-width: 600px) {
#rightSide {
display: block;
float: right;
}
/*THIS IS ON THE RIGHT SIDE*/
h2 {
font-size: 1.5em;
}
p {
font-size: 1em;
}
#leftSide {
display: none;
}
<div id="leftSide">
<h2>Post 1</h2>
<p>
Lorem ipsum dolor sit amet,
<br />consectetur adipiscing elit.
<br />Maecenas tempor eget ante at
<br />maximus. Vestibulum sed nulla
<br />ex. Sed congue maximus lectus,
<br />vel scelerisque eros.
</p>
<h2>Post 2</h2>
<p>
Lorem ipsum dolor sit amet,
<br />consectetur adipiscing elit.
<br />Maecenas tempor eget ante at
<br />maximus. Vestibulum sed nulla
<br />ex. Sed congue maximus lectus,
<br />vel scelerisque eros.
</p>
<h2>Post 3</h2>
<p>
Lorem ipsum dolor sit amet,
<br />consectetur adipiscing elit.
<br />Maecenas tempor eget ante at
<br />maximus. Vestibulum sed nulla
<br />ex. Sed congue maximus lectus,
<br />vel scelerisque eros.
</p>
</div>
<div id="rightSide">
<h2>Post #1</h2>
<p>
Lorem ipsum dolor sit amet,
<br />consectetur adipiscing elit.
<br />Maecenas tempor eget ante at
<br />maximus. Vestibulum sed nulla
<br />ex. Sed congue maximus lectus,
<br />vel scelerisque eros.
</p>
<h2>Post #2</h2>
<p>
Lorem ipsum dolor sit amet,
<br />consectetur adipiscing elit.
<br />Maecenas tempor eget ante at
<br />maximus. Vestibulum sed nulla
<br />ex. Sed congue maximus lectus,
<br />vel scelerisque eros.
</p>
<h2>Post #3</h2>
<p>
Lorem ipsum dolor sit amet,
<br />consectetur adipiscing elit.
<br />Maecenas tempor eget ante at
<br />maximus. Vestibulum sed nulla
<br />ex. Sed congue maximus lectus,
<br />vel scelerisque eros.
</p>
</div>
Here an answer to a question like yours.
I think you could divide your text in segments, each of a certain number of characters but without cutting any word.
Then you could put the first segment in the first page, the second on second page and so on...
The main problem is to trim yourBigText without cut any words, and here the solution I found on the other post helps.
var yourBigText = "CULIACAN, Mexico The Joaquin El Chapo Guzman story could hardly have seemed more unbelievable, with its multiple prison breaks, endless sewers and tunnels, outlandish sums of money and feverish manhunts. And then Sean Penn entered the story.While Guzman was the world's most-wanted fugitive, dodging Mexican military operations and U.S. Drug Enforcement Administration surveillance, he was secretly meeting with the Hollywood movie star in an undisclosed Mexican hideout and has now provided what appears to be the first public interview of his drug-running career, published Saturday by Rolling Stone."; //replace with your big text.
var cutLength;
var remainText = yourBigText.length;
var maxLength = 60;
while (remainText != 0) {
if (remainText >= maxLength) {
var trimmedText = yourBigText.substr(0, maxLength);
//re-trim if we are in the middle of a word
trimmedText = trimmedText.substr(0, Math.min(trimmedText.length, trimmedText.lastIndexOf(" ")));
//subtract from the original big string the length of the trimmedText
cutLength = trimmedText.length;
if (yourBigText.length > cutLength) {
yourBigText = yourBigText.slice(cutLength);
}
document.write(trimmedText);
document.write('<br>');
} else {
document.write(yourBigText);
exit();
}
remainText = yourBigText.length;
}
I hope this helps.
Related
I am using Axios to get data from an API. Then I am presenting the user with the data. The problem is that the text can be very lengthy and I wanted to add a line break after every "." for better presentation. Does anyone know a way to do it with CSS or any other way? Thank you. I'm using javascript by the way.
I am trying your code and my data is still not getting modified.
Am I making a mistake? I am new to js.
function App() {
const [cardChosen, setCardChosen] = useState(false);
const [cardName, setCardName] = useState("");
const [card, setCard] = useState({
passageName: "",
passages: "",
});
const searchCard = () => {
//this has been changed from the original
Axios.get(`https://bible-api.com/${cardName}`)
.then((response) => {
console.log(response);
setCard({
passageName: cardName,
passages: response.data.text,
passage: card.passages.replaceAll('. ', '.\n')
});
setCardChosen(true);
});
// addNewLines(card.passage);
};
// const addNewLines = () => {
// card.passage = card.passage.replaceAll('. ', '.\n');
// };
return (
<div className="App">
<div className="TitleSection">
<h1>Bible passages</h1>
<input type="text" onChange= {(event) => {
setCardName(event.target.value);
}}
/>
<button onClick={searchCard}>Search the Bible</button>
</div>
<div className="DisplaySection">
{!cardChosen ?
(<>
<h3> Please write the passage you want to read.</h3>
<h6>Format example: john 3:16</h6>
<h6>If you want several passages, write: john 3:1-16</h6>
</>)
:
(
<>
<h1>{card.passageName}</h1>
<h4>{card.passage}</h4>
</>
)}
</div>
</div>
);
}
export default App;
If you have the data as a string in javascript you can do this:
const myString = 'Hello, this is a string with one line. It will soon have 2 lines.'
const stringWithNewLines = myString.replaceAll('.', '.\n');
This will replace all occurrences of periods with a period followed by a new line (the \n is a newline). The new string is now:
Hello, this is a string with one line.
It will soon have 2 lines.
Notice there is a space at the start of the second line now, because there is a space following the period. If you want to get rid of the space do
const stringWithNewLines = myString.replaceAll('. ', '.\n');
So now it is replacing the space as well.
Note that replaceAll returns a new string and does not modify the original string.
I am fairly sure there is no way to do this in CSS, but if your string is already in javascript it will be very easy.
You need to add modify the text adding \n after each . (dot and space) with javascript.
const textFromAPI = 'Lorem ipsum. Dolor sit amet. Consectetur adipiscing elit.';
const modifiedText = textFromAPI.replaceAll(/\. /g, '.\n');
After that, you should put the text inside an element that has white-space: pre; or white-space: pre-wrap; CSS rule. More about white-space rule
<div style="white-space: pre;">
<!-- modifiedText goes here -->
</div>
You can achieve that in multiple ways, two of them are using:
string.prototype.split( ) and array.prototype.join( )
text = text.split('.').join('. <br/>');
string.prototype.replace( )
text = text.replace(/\./g, '. <br/>');
Please execute this snippet below. I've added some css, you can ignore it.
let text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum congue, enim sit amet dictum varius, purus massa tempus eros, eu porttitor magna tellus vel quam. In hac habitasse platea dictumst. Quisque sit amet placerat tortor, a euismod tortor. Phasellus eget placerat nisl, sit amet aliquet felis. Nulla lacus est, euismod vitae aliquam ut, mollis at odio. Cras tempor volutpat tellus, id sagittis orci mollis ut. Nulla aliquam mattis tortor. Curabitur lacus erat, ultrices in tempor sit amet, scelerisque sed risus. Nunc ultrices vulputate nisi, eu pulvinar neque laoreet auctor. Nunc ullamcorper nec enim in tincidunt. Duis sit amet viverra tellus, eu ultrices orci.';
const element = document.querySelector('.text');
//Either This
//text = text.split('.').join('. <br/>')
//or This
text = text.replace(/\./g, '. <br/>')
element.innerHTML = text;
#import url('https://fonts.googleapis.com/css2?family=Roboto:wght#300&display=swap');
.text{
font-size: 16px;
font-family: 'Roboto', sans-serif;
color:#ffeaa7;
}
.card{
border-radius: 0px 5px 0px 0px;
padding: 5px;
box-shadow: 0 5px 10px rgba(0,0,0,0.9);
background-color: #2d3436;
transition: all 0.2s;
}
<div class="card">
<p class="text"><p>
</div>
So I got some divs, which I split up with lettering.js. What this does is just splitting up an element into <span>s containing the single characters.
When I got a string with multiple words like "Hello World!", lettering.js will create a separate span for the space between the words. That span won't have a width, since its "empty" → there's no space between the words.
So theoretically I should be able to select those "empty" spans with span:blank (and manually setting a width for the space) since :blank selects whitespace aswell.
That didn't work tho.
So I tried using JavaScript, but even that failed.
I tried several methods:
$("span[class^='char']").each(function(){
// method 1:
this.innerHTML.trim();
// method 2:
$(this).text().trim();
// method 3:
$(this).text().replace(/\s/g, '');
// method 4:
$(this).text().replace(' ', '');
});
But all of those methods failed.
The selector isn't the problem. It selects every span I want it to.
Another method would just be to set a min-width for every span, which is pretty shabby tho and isn't always working nicely.
Anyone got an idea how I can get those "empty" <span>s to show as spaces?
Here's a link with a live example of the problem if you want to check it out.
Update: Removing display:inline-block from the span elements makes the space show up. I can't remove it tho, since the transform animation stops working properly without it.
You can use the :empty pseudo selector and add a space via content in CSS;
span:empty{
content:' ';
display: inline-block;
}
<span>A</span>
<span></span>
<span>B</span>
You can use letter-spacing to remove white space between the text.
<!DOCTYPE html>
<html>
<head>
<style>
div.a {
width: auto;
border: 1px solid black;
letter-spacing:0px
}
div.b {
width: 150px;
border: 1px solid black;
}
div.c {
width: 50%;
border: 1px solid black;
}
</style>
</head>
<body>
<h1>The width Property</h1>
<h2>width: auto (default)</h2>
<div class="a">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam semper diam at erat pulvinar, at pulvinar felis blandit. Vestibulum volutpat tellus diam, consequat gravida libero rhoncus ut. Maecenas imperdiet felis nisi, fringilla luctus felis hendrerit sit amet. Pellentesque interdum, nisl nec interdum maximus, augue diam porttitor lorem, et sollicitudin felis neque sit amet erat.</div>
</body>
</html>
I'm new to jQuery and I'd like to add a class to an individual image by hovering over a button - something I thought I knew how to do, turns out I don't.
The problem being I have several .service sections, each with their own .service button. Therefore, the end result is as expected: when I hover over the button, ALL the .service-image are affected. I thought I could resolve this by using $(this) or find() but I just cant figure it out...
$(".service button").hover(function() {
$(".service-image").toggleClass("raise");
});
.raise {
transform: translateY(-10px);
transition: all 0.2s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="service home-service1">
<div class="service-image">
<img src="images/phone.png" alt="" />
</div>
<div class="service-title">
<h2>Kiosk Renovation</h2>
</div>
<div class="service-text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut feugiat quam sit amet vehicula auctor. Aliquam vel orci hendrerit, vestibulum ligula laoreet, faucibus mi.</p>
</div>
<button class="outline-on-dark">Explore</button>
</div>
Since the <button> element is a sibling of the .service-image you're trying to target (i.e. they both share the same .service parent), you can use siblings(). By specifying the .service-image selector in the siblings() function, you can be sure to only ever target the .service-image inside of the .service element.
$('.service button').hover(function() {
$(this).siblings('.service-image').toggleClass('raise');
});
.raise {
transform: translateY(-10px);
transition: all 0.2s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="service home-service1">
<div class="service-image">
<img src="images/phone.png" alt="" />
</div>
<div class="service-title">
<h2>Kiosk Renovation</h2>
</div>
<div class="service-text">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut feugiat quam sit amet vehicula auctor. Aliquam vel orci hendrerit, vestibulum ligula laoreet, faucibus mi.</p>
</div>
<button class="outline-on-dark">Explore</button>
</div>
Try:
$('service button').on('hover', function(e){
$(this).siblings('.service-image').toggleClass('raise');
});
Your thinking was right, as both button and specific image share the same parent.
Here is my code.
<details>
<summary>1</summary>
Demo 1
</details>
<details>
<summary>2</summary>
Demo 2
</details>
<details>
<summary>3</summary>
Demo 3
</details>
What I want to do is -- if the details of any single <details> tag is open and I open/view another <details> tag, then the earlier one should close/hide/minimize.
How can this be achieved?
I'm aware the <details> tag is not supported in IE or Edge.
Another approach, slightly shorter, slightly more efficient, without dependencies, and without onclick attributes in the HTML.
// Fetch all the details element.
const details = document.querySelectorAll("details");
// Add the onclick listeners.
details.forEach((targetDetail) => {
targetDetail.addEventListener("click", () => {
// Close all the details that are not targetDetail.
details.forEach((detail) => {
if (detail !== targetDetail) {
detail.removeAttribute("open");
}
});
});
});
<details>
<summary>1</summary>Demo 1
</details>
<details>
<summary>2</summary>Demo 2
</details>
<details>
<summary>3</summary>Demo 3
</details>
Whao ! before my posting...
No one has ndicated that <details> elements work with the toggle event?
-- instead of click
-- and the toggle event also works with keyboard interaction.
No one has indicated that the open attribute is a boolean,
make it to true or false, don't do a .removeAttr("open") ;)
the doc : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details
const All_Details = document.querySelectorAll('details');
All_Details.forEach(deet=>{
deet.addEventListener('toggle', toggleOpenOneOnly)
})
function toggleOpenOneOnly(e) {
if (this.open) {
All_Details.forEach(deet=>{
if (deet!=this && deet.open) deet.open = false
});
}
}
<details>
<summary>1</summary>
Demo 1
</details>
<details>
<summary>2</summary>
Demo 2
</details>
<details>
<summary>3</summary>
Demo 3
</details>
The same thing in a shorter way with ES10? => .ontoggle direct event method
document.querySelectorAll('details').forEach((D,_,A)=>{
D.ontoggle =_=>{ if(D.open) A.forEach(d =>{ if(d!=D) d.open=false })}
})
See it in action : ( Plus some CSS improvements ;)
document.querySelectorAll('details').forEach((D,_,A)=>{
D.ontoggle =_=>{ if(D.open) A.forEach(d =>{ if(d!=D) d.open=false })}
})
details {
border : 1px solid lightgrey;
width : 24em;
padding : 0 .6em;
border-radius : .3em;
margin : .3em;
}
details > summary {
font-weight : bold;
margin : 0em -.6em;
list-style : none;
display : block;
padding : .5em;
}
details[open] {
padding-bottom : .6em;
}
details[open] summary {
border-bottom : 1px solid #aaa;
margin-bottom : .6em ;
}
summary::marker {
display : none;
}
summary::-webkit-details-marker {
display : none;
}
summary::after {
display : block;
float : right;
content : '\1405';
cursor : pointer;
transition : 180ms;
transform : rotate(90deg);
}
details[open] > summary:after {
transform : rotate(-90deg);
}
summary:hover {
outline : none;
background-color : whitesmoke;
}
<details>
<summary>Lorem ipsum one</summary>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor,
dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas
ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie,
enim est eleifend mi, non fermentum diam nisl sit amet erat.
</details>
<details>
<summary>Lorem ipsum two</summary>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor,
dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas
ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie,
enim est eleifend mi, non fermentum diam nisl sit amet erat.
</details>
<details>
<summary>Lorem ipsum three</summary>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor,
dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas
ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie,
enim est eleifend mi, non fermentum diam nisl sit amet erat.
</details>
Same concept, just a bit shorter.
$('details').click(function (event) {
$('details').not(this).removeAttr("open");
});
Yet another answer for those who don't want to use obsolete jQuery and those who loves functional javascript
[...document.getElementsByTagName("details")].forEach( (D,_,A) =>
D.addEventListener("toggle", E =>
D.open && A.forEach(d =>
d!=E.target && (d.open=false)
)
)
)
<details>
<summary>1</summary>Demo 1
</details>
<details>
<summary>2</summary>Demo 2
</details>
<details>
<summary>3</summary>Demo 3
</details>
Better late than never...
I would like to point out this quote from https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details
Note: You have to remove this attribute entirely to make the details hidden. open="false" makes the details visible because this attribute is Boolean.
(Read the note appended right at the end of the attributes paragraph.)
Apparently, in this case boolean means existing or not and not settable to true or false...
Browser magic going further!
I have come up with a solution. Please correct me if this is a wrong approach.
I added an onclick event to all of the details tag and made a function thisindex(this) which returns the index of the clicked tag and the obtained index number is then passed to the another function closeAll() which minimizes/closes all the other open tags except for one whose index matches with what we obtained earlier.
Here is the code.
function thisindex(elm){
var nodes = elm.parentNode.childNodes, node;
var i = 0, count = i;
while( (node=nodes.item(i++)) && node!=elm )
if( node.nodeType==1 ) count++;
return count;
}
function closeAll(index){
var len = document.getElementsByTagName("details").length;
for(var i=0; i<len; i++){
if(i != index){
document.getElementsByTagName("details")[i].removeAttribute("open");
}
}
}
<details onclick="closeAll(thisindex(this));">
<summary>1</summary>Demo 1
</details>
<details onclick="closeAll(thisindex(this));">
<summary>2</summary>Demo 2
</details>
<details onclick="closeAll(thisindex(this));">
<summary>2</summary>Demo 3
</details>
Same with the help of jQuery
$(document).ready(function(){
$('details').click(function (event) {
var index = $('details').index(this);
var len = $("details").length;
for(var i=0; i<len; i++){
if(i != index){
$("details")[i].removeAttribute("open");
}
}
});
});
Kindly suggest me a better approach if this not up to the mark.
Modification for use with polyfill jquery-details.js [Edge]
var isIE = /*#cc_on!#*/false || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
const details = Array.from(document.querySelectorAll("details"));
details.forEach((targetDetail) => {
targetDetail.addEventListener("click", () => {
details.forEach((detail) => {
if (detail !== targetDetail) {
if(isEdge) {
detail.className = detail.className.replace(/\bopen\b/g,"");
detail.open = false;
detail.querySelector("summary").setAttribute("aria-expanded","false");
var chil = detail.querySelectorAll("details > *");
for(var j = 0; j < chil.length; j++) {
if(chil[j].tagName != "SUMMARY") {
chil[j].style.display = "none";
}
}
} else {
detail.removeAttribute("open");
}
}
});
});
});**strong text**
Solutions offered appear less than clear to me.
Consider this instead:
const closeDetails = event => {
const targetDetails = event.target.parentElement;
const openDetails = document.querySelectorAll('details[open]');
for (const details of openDetails) {
if (details === targetDetails) continue;
details.removeAttribute('open');
}
};
const summaries = document.querySelectorAll('summary');
for (const summary of summaries) {
summary.addEventListener('click', closeDetails);
}
This production version follows the same thought process but is extended to cater for multiple accordions, and reduces the number of event listeners:
https://codepen.io/2kool2/pen/poOgxKb
I'm trying to create an FAQ list. The answer displays fine on first click but I want to be able to click on another question and have that answer expand and the other close. Here's the javascript:
$(document).ready(function() {
// hide all the answers
$('.faq li div').hide();
$('.faq li').click(function(){
var question = $(this);
var answer = $(this).find('div');
// if the faq isn't active
if(!$('.faq li').hasClass('active')) {
answer.slideDown();
$(this).siblings('div').slideUp();
question.addClass('active');
}
else {
answer.slideUp();
question.removeClass('active');
}
});
});
The CSS:
ul.faq {
list-style:none;
cursor:pointer;
z-index:1;
}
ul.faq li h3 {
background:#0A5C75 url(../images/faq-inactive.png) right no-repeat;
color:#fff;
padding:20px 50px 20px 10px;
margin-bottom:10px;
border:1px solid #fff;
}
ul.faq li.active h3 {
background:#0A5C75 url(../images/faq-active.png) right no-repeat;
}
ul.faq li div {
background:#FFFFFF;
margin:0px 10px 10px 10px;
padding:20px;
overflow:hidden;
/* added fixed width to stop the jerkyness*/
width:522px;
position:relative;
top:-10px;
box-shadow: inset 0px 4px 4px 0px rgba(63, 70, 76, 0.15), 0px 4px 4px rgba(63, 70, 76, 0.15);
}
and the HTML
<ul class="faq">
<li>
<h3>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut arcu magna, sodales vel dignissim pharetra, adipiscing sed orci?</a></h3>
<div>Vivamus rutrum arcu sit amet dolor pulvinar dictum. Etiam porttitor leo eget velit volutpat quis ultricies urna ornare. Quisque ac ultrices est. Ut lobortis malesuada justo, sed blandit sapien bibendum et. Donec vel ante eu orci pellentesque dictum. Phasellus molestie egestas du</div>
</li>
<li>
<h3>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut arcu magna, sodales vel dignissim pharetra, adipiscing sed orci?</a></h3>
<div>This is the answer to question 2</div></li>
<li>
<h3>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut arcu magna, sodales vel dignissim pharetra, adipiscing sed orci?</a></h3>
<div>This is the answer to question 3</div>
</li>
</ul>
I think I could improve on your code a bit and produce the behavior and also shorten the code by a fair bit.
Notice, I skipped using your active class in order to show how it could be achieved.
Here's a tinker.io for demo I tested it in FF13 and Chrome
$('.faq li div').hide();
$('.faq li').click(function(event) {
var clickedQuestion = event.target;
var answer = $(clickedQuestion).siblings('div');
if($('ul.faq').find('div').is(':visible')){
$('ul.faq').find('div').slideUp();
}
answer.slideDown();
});
Working demo http://jsfiddle.net/e3Bec/ OR http://jsfiddle.net/XGJXM/
Your code is fine only thing is use ==> if (!$(this).hasClass('active')) { instead of if(!$('.faq li').hasClass('active')) { :) Also you don't need this in your first conditional check question.addClass('active');
Rest code should help, :)
code
$(document).ready(function() {
// hide all the answers
$('.faq li div').hide();
$('.faq li').click(function() {
$('div').slideUp();
var question = $(this);
var answer = $(this).find('div');
// if the faq isn't active
if (!$(this).hasClass('active')) {
answer.slideDown();
$(this).siblings('div').slideUp();
//question.addClass('active');
}
else {
answer.slideUp();
question.removeClass('active');
}
});
});
I like that you are not sliding up the element if it is already visible.
Maybe move the .hide into css "display:none", no point waiting for the dom to load to hide them.
$(document).ready(function() {
$('.faq li').click(function(event){
$(this).find('div').not(":visible").slideDown();
$('.faq li div:visible').not($(this).find('div')).slideUp();
});
});
Why not use a Accordion. http://jqueryui.com/demos/accordion/