0

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.

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1, i would only add "And your click handler can actually be rewritten like this if there's no other code to run and no parameters to pass:"
1
var animateSideNav = function() {
  $(".side-nav").stop().animate({"margin-top": "0px"}, 450);
}

$(".side-nav ul li a").click(animateSideNav);

if(window.location.hash) {
  animateSideNav();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.