Grow your CSS skills. Land your dream job.

Toggling More Than 2 Text Items With JQuery

  • # January 22, 2013 at 5:49 pm

    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

    # January 22, 2013 at 6:18 pm

    (http://codepen.io/rosspenman/pen/qJcrb)

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

    # January 22, 2013 at 6:35 pm

    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

    # January 22, 2013 at 6:40 pm

    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.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".