\$\begingroup\$
\$\endgroup\$
1
I am a jQuery beginner and would like some pointers on whether the following code could be made shorter, or there is a better way to get the same result.
jQuery(document).ready(function(){
var aa=jQuery('#navigation-wrapper');
var bb=jQuery('#top');
jQuery(window).scroll(function(){
if(jQuery("body").hasClass("home")){
if(jQuery(this).scrollTop()>510){
aa.addClass("navbar-fixed-top");
//bb.css('marginTop', aa.height());
}
else{
aa.removeClass("navbar-fixed-top");
//bb.css('marginTop', 0);
}
}
else {
if(jQuery(this).scrollTop()>293){
aa.addClass("navbar-fixed-top");
//bb.css('marginTop', aa.height());
}
else{
aa.removeClass("navbar-fixed-top");
//bb.css('marginTop', 0);
}
}
});
});
Dan Oberlam
8,0392 gold badges33 silver badges74 bronze badges
-
\$\begingroup\$ As we all want to make our code more efficient or improve it in one way or another, try to write a title that summarizes what your code does, not what you want to get out of a review. Please see How to get the best value out of Code Review - Asking Questions for guidance on writing good question titles. \$\endgroup\$BCdotWEB– BCdotWEB2016年08月12日 12:35:09 +00:00Commented Aug 12, 2016 at 12:35
1 Answer 1
\$\begingroup\$
\$\endgroup\$
6
The code can made very short.
$(window).scroll(function () {
var scrollTop = $(document.body).hasClass('home') ? 510 : 293;
$('#navigation-wrapper').toggleClass('navbar-fixed-top', $(this).scrollTop() > scrollTop);
});
- There is no need of wrapping the code in
$(document).ready()
for binding events onwindow
. - Use ternary operator
- Use
toggleClass()
with second parameter to add/remove class based on a condition.
answered Aug 5, 2016 at 11:15
-
\$\begingroup\$ Did you just suggest the asker to go somewhere else, while at the same time preventing him with your answer from deleting his question? That's not ideal. \$\endgroup\$John Dvorak– John Dvorak2016年08月05日 11:19:49 +00:00Commented Aug 5, 2016 at 11:19
-
\$\begingroup\$ @JanDvorak No. I flagged the question for mod attention and asked them to migrate to CR.SE. \$\endgroup\$Tushar– Tushar2016年08月05日 11:20:35 +00:00Commented Aug 5, 2016 at 11:20
-
1\$\begingroup\$ Understood. A better option would have been to suggest the asker to delete the question and reask it somewhere else. That way the mods don't have to get involved. \$\endgroup\$John Dvorak– John Dvorak2016年08月05日 11:21:58 +00:00Commented Aug 5, 2016 at 11:21
-
\$\begingroup\$ @JanDvorak Right. That'll decrease burden on busy mods. Thanks. Will keep it in mind. :) \$\endgroup\$Tushar– Tushar2016年08月05日 11:23:14 +00:00Commented Aug 5, 2016 at 11:23
-
\$\begingroup\$ Does this not mean that the condition would only run if the body has a class of "home"? \$\endgroup\$ADRIAN– ADRIAN2016年08月05日 11:28:09 +00:00Commented Aug 5, 2016 at 11:28
lang-css