2

I have a html-document with a main navigation and a subnavigation consists of anchors. What I'm trying is to toggle a class to the anchor (subnavigation) while scrolling through the document.

With JQuery i tried the following:

$(function() {

    $(window).scroll(function () {

    //define position where i want to know the class
    var elem = document.elementFromPoint(400, 300) // x, y

    //read the class at position
    el = $(elem).attr('class');

    //get substring of last class in element
    //last classes are class_1, class_2, class_3, aso.
    subclass = el.substr(el.length-1); //throws an error "el is not defined"

    //toggle class
    $('a.class_'+subclass).toggleClass('additionalClass');


});

It works more or less. Here are my two questions:

  1. why does it throw an error "el is not defined"
  2. the result "flickers" because the there are many subsequent elements with the same class, e.g. "class_1". Can the actual value, e.g. "1" be stored as long there is not an other one is on the position where I read the classes?

Thanks for your help.

Fabian

  • Does `elem` exist? And from jQuery: As of jQuery 1.6, the `.attr()` method returns `undefined` for attributes that have not been set. – Marnix Dec 01 '11 at 12:42
  • And another problem maybe: you are asking for `document.elementFromPoint`. This will always be the same. I think you need to ask `window`, depending on your browser: http://www.zehnet.de/2010/11/19/document-elementfrompoint-a-jquery-solution/ – Marnix Dec 01 '11 at 12:43
  • `elem` exists. `window.elementFromPoint` does not work. When `.attr()` returns `undefined` i'd like that `subclass` does not change. I.e. that the last valid value is stored and returned until the next valid value is read. Thanks a lot. – Fabian Hefe Christen Dec 01 '11 at 12:53
  • If you have a correct answer on your question, answer the question yourself and accept it. This will keep stackoverflow clean. If I have given a correct answer in the comments: please say so and I will post my comment as an answer, so you can accept it. – Marnix Dec 01 '11 at 13:17
  • Thank you, Marnix, you're absolutely right. It declares `el` as undefined when `attr()` returns `undefined`. Regarding the "flickering": I have to use `addClass` and `removeClass` instead of `toggleClass`, otherwise it toggles everytime an item with the same value touches the position I'm reading. could you please set the answer and accept it. As a new user I can't do so for at least 8 hours after posting the question. Thanks. – Fabian Hefe Christen Dec 01 '11 at 15:06
  • You are the one that is going to accept it anyway if you are satisfied with my answer. I will post it now. – Marnix Dec 01 '11 at 17:34

1 Answers1

0

Quote from the jQuery website:

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set.

Be sure that there is a class attribute available.

Marnix
  • 6,384
  • 4
  • 43
  • 78