Reputation: 73
I am horrible at explaining on what I want, but ill give it a shot.
Ok here is html on the left side.
<div></div>
<div></div>
<div></div>
<div></div>
Here is what is outputting on the right side.
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
I am trying to make it so when you click the first div on the left, the first div on the right appears, and when u click second div on the left, the second div on the right appears while all the other divs on the right are hidden again and so on. I know you can do it with the .index() in jQuery, but I was wondering if i can get some help on how to do it. Thanks!
Upvotes: 1
Views: 81
Reputation: 123739
Something like this?
<div class="left">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div class="right">
<div class="block">Result 1</div>
<div class="block">Result 2</div>
<div class="block">Result 3</div>
<div class="block">Result 4</div>
</div>
$(function(){
$('.left > div').on('click', function(){
//Just show the respective block div based on the clicked index and hide its siblings that are visible.
$('.block').eq($(this).index()).show().siblings('.block:visible').hide();
});
});
With a little slide Effect
$(function () {
$('.block').eq(0).show();
$('.left > div').on('click', function () {
var elemToShow = $('.block').eq($(this).index()); //Get the element to show
$('.block:visible').stop().slideUp(1000, function () { // slide up the visible block div
elemToShow.stop().slideDown(1000); // once the animation finishes shidedown the element to show
});
});
});
Upvotes: 4
Reputation: 17061
Well, you first have to detect the click on the elements on the left. In the callback function, you'll have to find out the index of the clicked div and then show()
the one on the right side whose index matches the number.
Let's say you have the left divs inside a container with the class left
and the ones on the right inside right
:
$('.left').on('click', 'div', function(){ //bind the click event to the left divs
$('.right div') // select all the divs inside .right
.hide() // hide all the divs
.eq( $(this).index() ) // select the one that matches the clicked index
.show(); // show it
});
Here's a demo.
Here is the documentation for on()
.
Here is the documentation for eq()
.
Upvotes: 1
Reputation: 1417
Yes, you can try .index() and :eq() .index() returns the numeric index of an element, while :eq() returns the element by a numeric index.
Assume the left divs are inside a outer div with class 'left', and right divs inside 'right'
$('.left div').click(function () {
$('.right div').hide();
var i = $('.left div').index(this);
$('.right div:eq(' + i + ')').show()
});
Upvotes: 0
Reputation: 219920
Assuming you'll put a left
class on those left div
s:
var $blocks = $('.block'),
$left = $('.left');
$('.left').click(function () {
$blocks.hide().eq( $left.index(this) ).show();
});
Here's the fiddle: http://jsfiddle.net/YddrP/
Upvotes: 1