treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Toggling More Than 2 Text Items With JQuery

  • Hi, I am very new to Javascript and JQuery, however there is one simply thing I'm hoping to do on my site.

    I have a button called "stomp," and when it is clicked, I want the text in a span element above the button to display a different phrase. There are 12 phrases I want it to cycle through.

    I have managed to fudge some JQuery so far that toggles just 2 of the phrases. After searching through forums and StackOFlow and etc., I can't seem to find a simple fix for working it into 3-12 more phrases. I think I'm working in the wrong equation type (I feel like I shouldn't be using toggle). But I don't know where to go next. Any help would be awesome.

    (I am new to CodePen as well but have attempted to use and link it here):

    http://cdpn.io/FaepB

  • I forked your pen and made it work.

    Here's my JavaScript.

    $(function() {
      var texts = [
        "Your Business",
        "Your Budget",
        "Your Company",
        "Your Restaurant",
        "Your Organization",
        "Your Cause",
        "Your Band",
        "Your Store",
        "Your Bar",
        "Your Group",
        "You"
      ],
    
      $title = $("#myTitle");
    
      $("a").attr('data-last-text', 0).click(function() {
        var $this = $(this),
        textIndex = (parseInt($this.attr("data-last-text"), 10) + 1) % texts.length;
    
        $this.attr("data-last-text", textIndex);
    
        $title.text(texts[textIndex]);
      });
    });
    
  • Wish I knew the things you know that made this (probably) fairly easy to craft. Hopefully in due time.

    Many thanks for the help; it works perfectly.

    Peace -Bob

  • If you're interested, some things you could Google to help you learn about how it works are: Arrays, HTML5 data attributes, and the % (modulus) operator.