سؤال

I have a small FAQ where people can click on a question link and the answer appears nicely, using jQuery slideToggle().

The answers are hidden by default, you have to click on them to make them appear. I do not want to have an initial slide in when the page is loaded.

The problem is that people without JavaScript cannot make the answers appear. To allow these people to see them, they should be directly visible.

It is possible if I slide in the answers when the page is loaded, but I find the solution inelegant. Any idea how I could keep my solution ?

I made a jsFiddle here: http://jsfiddle.net/s5HNd/3/

My code:

HTML:

<div>
<ul class="faqquestions">
    <li>
        <span class="faqlink">First Question</span>
        <div class="faqreponse">First answer</div>
    </li>
    <li>
        <span class="faqlink">Second question</span>
        <div class="faqreponse">Second answer</div>
    </li>
</ul>
</div>

CSS:

ul.faqquestions li { cursor: pointer; }
div.faqreponse { overflow: hidden; }

JavaScript:

$(document).ready(function () {
    'use strict';
    $("ul.faqquestions li").each(function () {
        var tis = $(this), state = false, answer = 
            tis.children(".faqreponse").hide().css('height', 'auto').slideUp();

        $(this).children(".faqlink").click(function () {
            state = !state;
            answer.slideToggle(state);
        });
     });
});
هل كانت مفيدة؟

المحلول

With this question I discovered that the noscript tag can be but in the head and this is valid in HTML5. Moreover, styles can be written inside!

So the solution was to add this code between the head tags of the page:

<noscript>
<style>
    div.faqreponse {
        height: auto;
        overflow: visible;
    }
</style>
</noscript>

نصائح أخرى

You could have the answers visible by default, and on page load (or even when each answer element is loaded) you can hide the answers via JavaScript (you might have to use .slideToggle(0) which should slide them closed immediately). That way those with JavaScript can still slide the answers open/closed, but they will show for non-JS users due to not being closed in the first place.

Admittedly, since you have to wait until things are loaded this may not be visually pleasing for JavaScript users (which is the majority of Internet users out there). I would weigh this carefully with the noscript suggestion. Do you expect a significant portion of your audience to have JS disabled?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top