2

I am making a navigation bar for my client panel. It has many links on it. When a link is clicked, it will change what is shown in the main section of the screen. I need to be able to change the classes on each li entry in the ul (navigation bar).

This is my code, and it works:

$(document).ready(function() {

  function changeActive() {
    $('#elem1, #elem2').removeClass("active");
  }

  $('#main-section').load('src-pages/elem1.html');
  $('#elem1').addClass("active");

  $('li#elem1').click(function() {
    //load file now
    $('#main-section').load('src-pages/elem1.html');
    changeActive();
    $(this).addClass("active");
  });
  $('li#elem2').click(function() {
    //load file now
    $('#main-section').load('src-pages/elem2.html');
    changeActive();
    $(this).addClass("active");
  });
});

I am trying to make the file size as small as possible and would like to add the $(this).addClass("active"); line, into to the changeActive function. When I do add that line into the function, it doesn't work properly and only applies the :hover and :focus styles to the li or a element(s).

Could someone explain:

  1. Why that line ($(this).addClass("active");) doesn't work in the function
  2. How I could fix that line in order to put it inside the function

Thank you in advance.

1 Answer 1

2

I think the problem is you are trying to do $(this).addClass() inside the changeActive function.

If that is the case $(this) selector is not working because 'this' is a jquery reference for the element on which an event has been fired in this case.

You need to pass the 'this' to your other function and then it should work. Try:

function changeActive(el) {
    $('#elem1, #elem2').removeClass("active");    
    $(el).addClass('active');//el is the 'this' passed on from your event listener
}

$('li#elem1').click(function() {
    //load file now
    $('#main-section').load('src-pages/elem1.html');
    changeActive(this);
    //$(this).addClass("active");
  });
Sign up to request clarification or add additional context in comments.

1 Comment

@JoshMurray Definitely look into how this works in Javascript. It's not identical to most other languages, and has bitten me more than once. A good understanding will save you from pain down the road

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.