Josh Murray
Josh Murray

Reputation: 637

jquery - change class function

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.

Upvotes: 2

Views: 223

Answers (1)

Anubhab
Anubhab

Reputation: 741

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");
  });

Upvotes: 2

Related Questions