1

I'd like to check if a div with a particular href has a certain class too. I've coded this nav:

<nav>
    <div class="nav-wrapper">
        <ul class="normal-nav hide-on-med-and-down">
            <li><a class="" href="#chi">Chi Siamo</a></li>
            <li><a class="" href="#dirigenza">Dirigenza</a></li>
            <li><a class="" href="#squadre">Squadre</a></li>
            <li><a class="" href="#orariPrezzi">Orari e Prezzi</a></li>
            <li><a class="" href="#modulistica">Modulistica</a></li>
            <li><a class="" href="#contatti">Contattaci</a></li>
            <li><a class="" href="#fotogallery">Fotogallery</a></li>
        </ul>
    </div>
</nav>

A class active is added to the <a> element, relative to location on which the user has scrolled down, so that <a> looks like this:

<a class="active" href="#dirigenza">Dirigenza</a>

I'd like to check continuously which element in normal-nav <ul> has class active (I've scrollFire() JQuery plugin):

$('body').scrollfire({
    // Offsets
    offset: 0,
    topOffset: 0,
    bottomOffset: 0,
    onScrollAlways: function(elm, distance_scrolled) {
    },
});

and do some stuff if <a> active element is that one with href="#chi", href="#dirigenza" and so on.

How can I do this?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Wonderman
  • 931
  • 10
  • 21

3 Answers3

2

You can use $("a.active") to get the current a marked as active. Then you can use $("a.active").attr("href") to get the value of the href for that active element and use it in a if or switch statement to manage different cases.

var activeHrefValue = $("a.active").attr("href");
if (activeHrefValue == "theValueToBeChecked") {
   doSomething();
}

In your particular case I think this can be a good solution:

$('body').scrollfire({
    // Offsets
    offset: 0,
    topOffset: 0,
    bottomOffset: 0,
    onScrollAlways: function(elm, distance_scrolled) {
        switch($("a.active").attr("href")){
            case "#chi":
                doSomething(elm);
                break;
            case "...":
                doSomethingElse(elm);
                break;
            default: 
                doDefaultSomething(elm);
        }
    },
});

That switch part can be replaced with a series of if-else statements based on your necessities.

LucioB
  • 1,744
  • 1
  • 15
  • 32
0
$("a.active[href='#chi']")

Will select all a with class active and whose href is #chi.

$("a.active[href='#chi'], a.active[href='#dirigenza']")

Use this one for multiple hrefs

$("a.active[href='#chi']").length 

will give the number of matching elements.

void
  • 36,090
  • 8
  • 62
  • 107
0

You can use hasClass method:

$('body').scrollfire({
    // Offsets
    offset: 0,
    topOffset: 0,
    bottomOffset: 0,
    onScrollAlways: function(elm, distance_scrolled) {
      if($(elm).hasClass('testingclass')){
         console.log('testingclass');
      }
    },
});
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231