Felicyia Felicyia - 7 months ago 38
Javascript Question

jquery hide div, show another, on click

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.

hmd hmd
Answer

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/