How to toggle a text


#1

https://www.codecademy.com/courses/learn-javascript/lessons/javascript-dom/exercises/slide-toggle?action=lesson_resume

Hello all,

(sorry for my english first of all)

In that Javascript/DOM final lesson, text ‘Recent Projects’ is changed to 'Projects Viewed’
when the button is clicked, but anyone has a suggestion to change the text back to 'Recent Projects’
when the tree is hidden, and then to ‘Projects Viewed’ again?
(it does not matter now if that action really makes sense in that context,
I think you know the goal of my question, basically how to change from text A to text B after clicking
and from text B to text A after the second click, etc, etc.)

Thank you!!


#3

Please post your code so we can review it and make recommendations. Thanks.


#4

Hi Roy,

function main(){
  $('.skillset').hide();
  $('.skillset').fadeIn(1000);  
  $('.projects').hide();
  $('.projects-button').on('click', function(){
    $(this).next().slideToggle(400);
    $(this).toggleClass('active');
    $(this).text('Projects Viewed');
  });
}
$(document).ready(main);

In the line in bold the text is changed to ‘Projects Viewed’ but it remains that way forever (unless the whole page is reloaded). I wonder how to make that the text changes to ‘Recent projects’ when the projects tree is hidden (so when hidden -> text ‘Recent Projects’ and when visible text -> ‘Projects Viewed’)… I hope my explanation is clear :slight_smile :slight_smile:

Thank you.


#5

One approach would be test if the active class is set.

    $(this).toggleClass('active');
    if ($(this).hasClass('active')) {
      $(this).text('Projects Viewed');
    } else {
      $(this).text('Projects');
    }

#6

It works perfectly. That’s exactly the behaviour I was expecting.

I didn’t know that method (hasClass;I’ve been learning more about it at the jQuery API documentation)

Thank you very much!!


#7

This topic was automatically closed after 7 days. New replies are no longer allowed.