0

I have the following code which applies classes to the <nav> element. The code works so no issues there.

$(document).ready(function() {

$(window).scroll(function() {

    if ($(window).scrollTop() > 300) {
        $('nav').addClass('stick');
        $('nav').css('top','0');
    }

    if ($(window).scrollTop() < 300) {
        $('nav').removeClass('stick');
        $('nav').css('top', '0');
    }

});

});

however I use two elements in my website so I only want the code to apply to this specific nav

html

<nav role="main-navigation">   ...  </nav>

As well, I would also like the code to ONLY apply to this nav element on screens >768px

user3550879
  • 3,389
  • 6
  • 33
  • 62

2 Answers2

1

$('nav')[0] --> it identifies specific nav tag.. without using id we can specify like this.

$(document).ready(function() {

$(window).scroll(function() {

    if ($(window).scrollTop() > 300) {
        $('nav')[0].addClass('stick');
        $('nav')[0].css('top','0');
    }

    if ($(window).scrollTop() < 300) {
        $('nav')[0].removeClass('stick');
        $('nav')[0].css('top', '0');
    }

});

});
Senthil Kumar
  • 562
  • 1
  • 6
  • 14
1

1/ "Want the code to apply to this specific nav " If you don't want to add more attribute (id, class) you can use Attribute Equals Selector

$("nav[role='main-navigation']").

2/ "ONLY apply to this nav element on screens >768px" Reference to this answer

if (window.matchMedia('(min-width: 768px)').matches) {
    //...
} else {
    //...
}