0

I have some problems converting the CSS id to a class and the javascript to match it. I need to use the script multiple times on the site

Here my code: CSS:

#first {
    background-color: #FFF;
    width: auto;
    height: auto;
    overflow: hidden;
    padding: 10px;
} 

JavaScript:

var divh = document.getElementById('first').offsetHeight;

//keep default height
var divh = $("#first").outerHeight();

document.getElementById("first").style.height = "100px";

//toggle functions
$('div:first').toggle(
  function () {
     $("#first").stop().animate({
        height: divh +'px'
     }, 1000);
  },
  function () {
    $("#first").stop().animate({
      height: '100px'
    }, 1000);
  }
)
1
  • What do you want it to do, and what is the (presumably wrong) result you're getting? Commented Feb 17, 2011 at 11:17

4 Answers 4

1

If I understand correctly you can just do:

.first {
    background-color: #FFF;
    width: auto;
    height: auto;
    overflow: hidden;
    padding: 10px;
}

And the Javascript would be something like this:

var divh = $('.first').offsetHeight;

//keep default height
var divh = $(".first").outerHeight();

$('.first').style.height = "100px";

//toggle functions
$('div:first').toggle(
  function () {
     $(".first").stop().animate({
        height: divh +'px'
     }, 1000);
  },
  function () {
    $(".first").stop().animate({
      height: '100px'
    }, 1000);
  }
)

Just uses the jQuery selector to select the class instead of the ID.

Sign up to request clarification or add additional context in comments.

2 Comments

What exactly "doesn't work"? Have you tried running in Firefox using Firebug, it will show you any Javascript errors.
The slide does not animate anymore.
1

I think you can use a "class selector" to get all the elements belonging to that class and then apply animation to all of them or one by one by using the each function (see here). Something like:

CSS

.first {
background-color: #FFF;
width: auto;
height: auto;
overflow: hidden;
padding: 10px;
} 

JavaScript:

$('.first').each(function () {
    var divh = $(this).outerHeight();
    ecc. ecc.
})

1 Comment

If you call the toggle() function (or any other function for that matter) using the class selector it will be applied to all elements matching that class.
0

use .first instant of #first

Comments

0

Mark's answer is almost entirely correct.

Although, he changed $('div:first') to $('div.first') which are not the same thing.

:first is part of jQuery selectors to select only the first matched element (see here).

So, if you want to pick the first div, use $('div:first'). If you want to select all divs with the "first" class, use $('div.first').

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.