Dean Elliott
Dean Elliott

Reputation: 1533

Add style to an element with Javascript

I've added a simple jquery slideDown function to a client's website but they want to add some style via javascript so that for anyone with JS disabled they still see the content.

<script>
    $(".click").click(function () {
        $(".morecontent").slideToggle("slow");
    });
</script>

.morecontent is currently set to display:none via the stylesheet, so basically I want to include this style in the script as oppose to the stylesheet

Upvotes: 0

Views: 5519

Answers (4)

Rich O&#39;Kelly
Rich O&#39;Kelly

Reputation: 41767

Use this:

$('.morecontent').hide();

Upvotes: 0

Abdul Munim
Abdul Munim

Reputation: 19217

<script>
    $(".morecontent").css ( {display: "none" } );
    $(".click").click(function () {
        $(".morecontent").slideToggle("slow");
    });
</script>

Upvotes: 0

Richard Dalton
Richard Dalton

Reputation: 35793

Remove the display:none in the style sheet and hide the elements with the class morecontent using jQuery when the page loads:

<script>
    $(".morecontent").hide();
    $(".click").click(function () {
        $(".morecontent").slideToggle("slow");
    });
</script>

This might cause a flicker as elements are hidden when the page is loaded. You can get around this by hiding the entire page $('body').hide(); at the top of the page and showing it again at the bottom.

Upvotes: 0

Rob W
Rob W

Reputation: 349142

To set the CSS using jQuery, use:

$(".morecontent").css("display", "none");

The display:none property can also be set by using .hide(). Note: You should call this code when the document is ready, ie, the element is already defined. To achieve this, use:

$(document).ready(function(){
    $(".morecontent").hide();
})

When JavaScript is disabled, the elements will be visible (because the display:none at the stylesheet has been removed). When JavaScript is enabled, the script will hide the .morecontent, so that it can be slided in.

Upvotes: 1

Related Questions