Reputation: 76
I have a side navigation that, upon clicking a link, will do a certain function:
$(".side-nav ul li a").click(function(event) {
$(".side-nav").stop().animate({"margin-top": "0px"}, 450);
});
I also have this same function trigger if the page loading has a hashtag
if(window.location.hash) {
$(".side-nav").stop().animate({"margin-top": "0px"}, 450);
}
What I am looking for is a way to combine the two to reduce redundancy.
If the url has a hashtag, trigger the function, else only trigger the function if a sidenav item is clicked.
I can't seem to wrap my head around this. Any help would be much appreciated.
Thank you.
Upvotes: 0
Views: 173
Reputation: 48789
Put the code in a function and invoke it in both places.
function sideNav() {
$(".side-nav").stop().animate({"margin-top": "0px"}, 450);
}
$(".side-nav ul li a").click(function(event) {
sideNav();
});
if(window.location.hash) {
sideNav();
}
And your click
handler can actually be rewritten like this if there's no other code to run:
$(".side-nav ul li a").click(sideNav);
If there are any arguments that need to be passed to sideNav
, then this rewrite won't be suitable. They would need to be manually passed from within a click handler that invokes the function.
Upvotes: 4
Reputation: 23262
var animateSideNav = function() {
$(".side-nav").stop().animate({"margin-top": "0px"}, 450);
}
$(".side-nav ul li a").click(animateSideNav);
if(window.location.hash) {
animateSideNav();
}
Upvotes: 1