Reputation: 139
I found some jQuery to help me with showing and hiding a div
display. What's supposed to happen is that when one link is clicked, it hides the first div
and shows the second. I found several ways to do this but it breaks the whole page only showing the footer and nothing else on the page every time. It looks really weird, but i don't know enough about jQuery to fix it so any assistance would be greatly appreciated!
$('a').click(function(e) {
e.preventDefault();
$('div').eq($(this).index()).show();
$('div').not($('div').eq($(this).index())).hide();
});
.hide {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<a href='#'>link1</a>
<a href='#'>link2</a>
<a href='#'>link3</a>
<div> div for link 1</div>
<div class="hide"> div for link 2</div>
<div class="hide"> div for link 3</div>
http://www.embroiderywear.com/designshirtsonline1.html Here's the test page so you can see how it's messing up (or the solution if it gets fixed) I'm using foundation 5 for the frame work so i'm not sure if it's something there that's breaking it or something else.
Upvotes: 0
Views: 2471
Reputation: 87203
$('div')
will select all the <div>
elements on the page.
You can
wrap the div
elements of interest in a container
<div id="container">
<div> div for link 1</div>
<div class="hide"> div for link 2</div>
<div class="hide"> div for link 3</div>
</div>
And in JavaScript, use
$('#container div').eq($(this).index()).show() // Show the corr. el
.siblings().hide(); // Hide other
add a common & unique class on all the div
elements of interest
<div class="myClass"> div for link 1</div>
<div class="hide myClass"> div for link 2</div>
<div class="hide myClass"> div for link 3</div>
and in JavaScript
$('.myClass').eq($(this).index()).show()
.siblings().hide();
and use the selector to select only those elements.
Upvotes: 1
Reputation: 970
As @Tushar already mentioned, you need to make a Container that will wrap all of your divs and then you can play with your Javascript/JQuery:
HTML:
<a href='#'>link1</a>
<a href='#'>link2</a>
<a href='#'>link3</a>
<div id="divContainer">
<div> div for link 1</div>
<div class="hide"> div for link 2</div>
<div class="hide"> div for link 3</div>
</div>
Javascript/Jquery:
$(document).ready(function(){
$('a').click(function(e) {
e.preventDefault();
$('div#divContainer div').hide();
$('div#divContainer div').eq($(this).index()).show();
});
});
CSS:
.hide {
display:none;
}
Working Demo: http://jsfiddle.net/boq0c76f/
Upvotes: 1