0

I have set of tabs with text and icons. The active tabs have a white background with blue text and icons. The other tabs are the opposite. What I want to do is simply dynamically change the icons when they are active. The blue icon works, but doesn't change to white when not active.

Here's what I have:

if ($('#project_details').hasClass('active')) {
    $('#tab1').attr('src','img/blue.png');
} else {
    $('#tab1').attr('src','img/white.png');
}

HTML:

<li id="project_details" class="active">
<img src="" id="tab1">Project Details</li>
3
  • 1
    Code looks fine, I'm just wondering what event triggers your code to execute? Commented Nov 19, 2014 at 18:03
  • You'll need to either 1) use CSS and background images instead, which doesn't rely on events, or 2) share what mechanism you're using for the tabs so we can help construct an event callback. Commented Nov 19, 2014 at 18:08
  • I am using the bootstrap jquery for tabs (getbootstrap.com/javascript/#tabs) Commented Nov 19, 2014 at 18:11

1 Answer 1

1

The active class is already added and removed from the element automatically by the browser, this is because it's a css pseudo-class. Your code to change the src attribute looks fine, but I don't see anything which would trigger your code to run. (Note: this is a response to previous answers telling OP to add/remove active manually.)

When exactly do you want this if statement to execute? When a user clicks on another tab? If so, I would use jQuery to create an event handler for the click event of a tab.

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

2 Comments

i tried an .on('click') but it didn't work. is that what you're referring to?
Indeed, I would reccomend you identify a common element which groups your tabs, such as the parent ul element. You can create a selector such as $('ul li').on('click', function(e){ //code }); So any click on a li inside your ul will trigger a block of code.

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.