Argoron
Argoron

Reputation: 759

Select non-adjacent element with jquery

I have an html file which is structured pretty much this way:

<div id="text-container">
   <h1>Title 1</h1>
   <div class="text"></div>
   <div class="text"></div>
   <div class="text"></div>
   <div class="text"></div>
   <h1>Title 2</h1>
   <div class="text"></div>
   <div class="text"></div>
   <div class="text"></div>
   <h1>Title 3</h1>
   ...
 </div>

The files are built dynamically, so number of titles and text-class divs can vary. What I am trying to achieve is to insert a elements in order to be able to jump from one title to the next, so I'm sort of after a prev() or next() but without the elements having to be siblings.

Can anyone please point me in the right direction ?

Thanks in advance for your help

Upvotes: 2

Views: 153

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206565

Here it is: using some ternary operators: (just add a class btn to your .prev and .next buttons)

DEMO

$('h1').each(function(){
   $(this).data('myTopPosition', $(this).position().top );
});

var howMany = $('h1').length;
var curr = 0; // zero based so the first 'H1' is actually '0'

function correct(){
    var corr = curr === -1 ? curr=howMany-1 : curr = curr%howMany;
}

$('.btn').click(function(){
  var whatBtn= $(this).hasClass('next') ? curr++ : curr-- ;
    correct();
    var goToPos = $('h1').eq(curr).data('myTopPosition');
    $('html, body').stop().animate({ scrollTop: goToPos },1500);
});

Upvotes: 2

Kevin B
Kevin B

Reputation: 95064

If you want .next() functionality that goes beyond the immediate next element, try .nextUntil + .next

$("#text-container").click(function() {
    var $nextTitle = $(this).nextUntil("h1").next();
    alert($nextTitle.text());
});

Upvotes: 3

Related Questions