Developer Vidit
Developer Vidit

Reputation: 70

How can I show/hide more than 2 span classes and toggle between them in Jquery?

I want to toggle between more than 2 span classes and initially it displays only one class. Is it possible to do it with the help of Jquery. If not, any other way to solve my problem.

Sample HTML code

<li class="symbol"><span class="off">`</span><span class="on">~</span></li>

Sample Jquery code

$('.symbol span').toggle();

This code works fine.

Working Fiddle

But what I want is

<li class="symbol"><span class="off">`</span><span class="on">~</span>
<span class="hinoff">a</span><span class="hinon">b</span></li>

and some Jquery code to toggle between these 4 span classes and initially displaying only one.

It means initially it displays any of the span class, let's say span class = "off" and it is showing '`'. Now I want to toggle to my class on clicking on my element to let's say span class = "hinoff" and it should show 'a'.

Upvotes: 3

Views: 370

Answers (2)

Drecker
Drecker

Reputation: 1265

To show selected span and hide all others, just hide them all and show the one you want:

$('.symbols span').hide();
$('.symbols span.' + selectedClass).show();

Upvotes: 2

AlliterativeAlice
AlliterativeAlice

Reputation: 12577

Calling this function should show the next span and hide the others no matter how many spans there are.

function showNext() {
    var $shownElement = $('.symbol span:visible').first();
    var $elementToShow = $shownElement.next();
    console.log($elementToShow);
    if (!$elementToShow.length) $elementToShow = $('.symbol span').first();
    var $shownElement = $('.symbol span:visible');
    $('.symbol span').hide();
    $elementToShow.show();
}

Fiddle demo

Upvotes: 2

Related Questions