Go to the next element with next and add a class to the previous one

Asked

Viewed 8,971 times

4

I’m trying to make sure that by clicking on the "next" link, one of my lists is revealed and the previous one is hidden, using a class that has display: none;, tried with .next() of jQuery but there were some problems, as, for example, in a div with 3 Uls he jump from the first to the last.

http://jsfiddle.net/5kkxy/

<div class="content">
<a href="#" class="prev">anterior</a>

    <div class="representante-info">
        <div id="#rep-info" class="texto">
            <ul>
                <li>
                    <h2>foo LTDA</h2>
                </li>
                <li>End: Alameda dos Anjos 233, São Caetano do Sul - SP</li>
                <li>Cep: 1234-000</li>
                <li>Fone: (11) 1234-0000</li>
                <li>Site: www.foo.com.br</li>
                <li>E-mail: [email protected]</li>
            </ul>
            <ul class="hidden">
                <li>
                    <h2>FOO LTDA</h2>
                </li>
                <li>End: Rua do Bosque, 222, São Paulo - SP</li>
                <li>Cep: 1234-000</li>
                <li>Fone: (19) 8845-9897</li>
                <li>Site: www.foo.com.br</li>
                <li>E-mail: [email protected]</li>
            </ul>
            <ul class="hidden">
                <li>
                    <h2>Jhon Doe</h2>
                </li>
                <li>Rua Plesk, 400 São paulo - SP</li>
                <li>Cep: 1234-000</li>
            </ul>
        </div>
    </div>
    <!-- /.representante-info --> <a href="#" class="next">proximo</a>

</div>

CSS:

.content {
    width: auto;
    height: 750px;
    margin: 0 auto;
}
.content a.prev, a.next {
    float: left;
    display: block;
    width: 31px;
    height: 27px;
    color: #f26;
    position: relative;
}
.content a.prev {
    background-image: url(../assets/img/setas.png);
    background-repeat: no-repeat;
    background-position: 0 0;
    top: 50px;
    margin: 0 10px 0 0;
}
.content a.next {
    background-image: url(../assets/img/setas.png);
    background-repeat: no-repeat;
    background-position: 0 -27px;
    top: 50px;
    margin: 0 0 0 10px;
}
.content .representante-mapa {
    width: 850px;
    height: 560px;
}
.content .representante-info {
    width: 650px;
    height: 134px;
    background-color: #df6225;
    background-image: url(../assets/img/rep-map-info.png);
    background-position: -1% 50%;
    background-repeat: no-repeat;
    margin: 0 auto;
    float: left;
}
.content .representante-info .texto {
    width: 328px;
    height: 100%;
    margin: 0 0 0 60px;
}
.content .representante-info .texto ul {
    list-style-type: none;
    margin: 0;
    padding: 0 0 0 20px;
}
.content .representante-info .texto ul.hidden {
    display: none;
}
.content .representante-info .texto ul li {
    font-family:'helvetica neue', arial, sans-serif;
    font-size: 14px;
    color: #fff;
}
.content .representante-info .texto ul li h2 {
    font-family: arial, serif;
    text-transform: uppercase;
    font-size: 16px;
    color: #fff;
    padding: 0;
    margin: 0;
}

3 answers

7


If your problem is in the code in jQuery, you should have the same question!

Problem with HTML

You have an HTML problem, the id of your element that surrounds the various lists contains the character # the most:

<div id="#rep-info" class="texto">

Should be:

<div id="rep-info" class="texto">

Cycle navigation with jQuery

In order to navigate "in a circle" through the various lists, you have to walk to the next element, but check whether the current element is the last one or not, so you can return to the first element, creating the loop desired. The same applies if you are using reverse navigation.

Example working on Jsfiddle

var $list = $('#rep-info'); // elemento que contém as ULs

$('.prev, .next').on("click", function(e) {
    e.preventDefault();

    var $item = $list.find('ul:not(.hidden)'); // apanha quem está visivel

    $item.addClass('hidden'); // esconde todos

    if ($(this).hasClass('next')) { // andar para o próximo
        if ($item.is(':last-child')) { // se for a última UL
            $list.find('ul:first-child').removeClass('hidden');
        } else {
            $item.next().removeClass('hidden');
        }
    } else { // andar para o anterior
        if ($item.is(':first-child')) { // se for a primeira UL
            $list.find('ul:last-child').removeClass('hidden');
        } else {
            $item.prev().removeClass('hidden');
        }
    }
});
  • +1 for good solution and ID error :)

  • @Zuul thank you so much for your reply, you thought in all the details. inclusive pointed me out about my error in the element ID!

  • should be the best solution but I swear I didn’t understand anything, kkkkk :/

  • is because each one has a different way of arriving at a solution, in his logic is very close to what I was trying before, but yours also works. here the project as it is getting http://bit.ly/1gXSuO8

5

Here’s another alternative, using only the class hidden as you suggested:

$('.next, .prev').on('click', function (event) {
    event.preventDefault();
    trocar($(this).hasClass('next')); // chama a função passando true ou false consoante seja o botao next ou prev
});

function trocar(index) {
    var ul = $('ul');   // por em cache todos os ul
    var visivel;        // iniciar a variavel que vou usar para saber qual está visivel, ie: não hidden
    ul.each(function (i) { // um ciclo para verificar todos os ul
        if (!$(this).hasClass('hidden')) {  // no caso de não ter a classe
            if (!index && i == 0) {         // no caso de prev e ser o primeiro elemento
                visivel = ul.length - 1;    // dar o index do ultimo elemento à variavel "visivel"
            } else if (index && i == ul.length - 1) { // no caso de proximo e de ser o ultimo elemento
                visivel = 0;  // voltar ao principio
            } else {
                visivel = i + (index ? 1 : -1); // casos intermédios
            }
        }
    })
    ul.addClass('hidden'); // esconder todos
    ul.eq(visivel).removeClass('hidden'); // não esconder o escolhido como visivel
};

Example

In the example is an improved version of the code. Compressed by Zuul™

  • I can’t click my mouse to vote for your answer... I think it has to do with the absence of a superficial explanation of the code! ;)

  • Swedish mice are much better :) But I’ll add a few comments now that I’ve been able to compress the code a little bit more :)

  • @Zuul, already edited. Take a look and edit what you find :))

  • I just "compressed" the two events of click to one in order to further reduce the code, something like: $(this).hasClass("next") ? troca(1) : troca(0), but +1

  • @Zuul, good idea. I’m just afraid there are others <a>.

  • your answer is also correct!

Show 1 more comment

2

You can yes, using the .next() of and also the .prev() however you will need to check if there is a next/previous element before leaving doing what you have to do, and also changed some things in HTML, in case the code would be this:

$('.next').click(function(){
    var el = $('.active');
    if (el.next().length > 0){
        el.addClass('hidden');
        el.next().removeClass('hidden');
        el.next().addClass('active');
        el.removeClass('active');
    }
});

$('.prev').click(function(){
    var el = $('.active');
    if (el.prev().length > 0){
        el.addClass('hidden');
        el.prev().removeClass('hidden');
        el.prev().addClass('active');
        el.removeClass('active');
    }
});

And on the HTML, you have to put one <ul class=active> by default, that is, you have to leave one of the <ul> with class "active" when loading the page.

Example running on Jsfiddle

  • 1

    thanks for the effort :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.