Reputation: 17671
Can anyone tell me what I'm doing wrong here -
I want the following script to react only if the div with id #main-nav doesnt also have the class .scrolled
$(window).scroll(function(){
if ($(window).scrollTop()< ($(window).height()-50)){
if (!("#main-nav".hasClass('submenu'))){
$('#main-nav').removeClass('scrolled');
alert ("REMOVED")
}
}
else{
if (!"#main-nav".hasClass('submenu')){
$('#main-nav').addClass('scrolled');
}
}
});
Upvotes: 0
Views: 337
Reputation: 36702
You have a few syntax errors...
$(window).scroll(function(){
if ($(window).scrollTop()< ($(window).height()-50)){
if (!("#main-nav".hasClass('submenu'))){ // missing "$". Missing ")". Extra ")" near end
$('#main-nav').removeClass('scrolled');
alert ("REMOVED")
}
}
else{
if (!"#main-nav".hasClass('submenu')){ // Missing "$(". Missing ")"
$('#main-nav').addClass('scrolled');
}
}
});
Try this:
$(window).scroll(function(){
if ($(window).scrollTop()< ($(window).height()-50)){
if (!$("#main-nav").hasClass('submenu')){
$('#main-nav').removeClass('scrolled');
alert ("REMOVED");
}
}
else{
if (!$("#main-nav").hasClass('submenu')){
$('#main-nav').addClass('scrolled');
}
}
});
Upvotes: 1
Reputation: 29932
"#main-nav"
is a string and strings in JS do not have a function like hasClass
.
You have to pass that selector/string into the jQuery (or find) function to get a jQuery object. Afterwards you may check with hasClass
:
if( !jQuery("#main-nav").hasClass( 'submenu' ) )
On the other hand, you could as well only select that element with a single selector:
if( jQuery("#main-nav.submenu").length > 0 )
Also, if you are re-using the same element multiple times, you should store it in a variable, because each call to jQuery/$
will trigger a scan over the DOM which is a very costly operation.
var mainNav = jQuery( '#main-nav' );
if( !mainNav.hasClass( 'submenu' ) )
Upvotes: 1
Reputation: 539
Put the $() selector like this
if (!$("#main-nav").hasClass('submenu')){
Upvotes: 1