user153923
user153923

Reputation:

jQuery does not find <div> by class

I am attempting to display my animated controls relative to the position of my form's header.

<div class="page-header container">

From within jQuery, I am trying to show messages with this function:

function showMessage(stype, title, message) {
  var position = $('.page-header container').offset.top;
  if (typeof position == 'undefined') {
    position = '50px';
    alert(position);
  } else {
    position = "'" + position + "px'";
  }
  $('.' + stype).animate({ top: position }, 500);
}

Every time I get alert('50px').

Since I am identifying with a CLASS instead of an ID, I thought I would try reading in the collection of all items in class '.page-header container':

function showMessage(stype, title, message) {
  var items = $('.page-header container');
  var position = items[0].offset.top;
  if (typeof position == 'undefined') {
    position = '50px';
    alert(position);
  } else {
    position = "'" + position + "px'";
  }
  $('.' + stype).animate({ top: position }, 500);
}

This time, it seems that items is undefined.

What have I overlooked?

Upvotes: 0

Views: 58

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074585

Two problems with this line:

var position = $('.page-header container').offset.top;

First, it's looking for an element with the tag container within an element with the class page-header. The space indicates a descendant combinator. Second, offset is a function, not a property.

I think you meant:

var position = $('.page-header.container').offset().top;

That looks for an element that has both of the classes page-header and container, and calls offset (because it's a function), and then uses the top property of the object it returns.

Upvotes: 7

Related Questions