Reputation: 6057
I am trying to get a working nav-bar that hides/shows and svg
element. JQuery, however does not respond correctly. My code is as follows:
HTML
<header id="header"><h1 class="title">Test</h1></header>
<nav id="nav">
<p class="text" data-index="0">Test</p>
<p class="text" data-index="1">Test</p>
<p class="text" data-index="2">Test</p>
<p class="text" data-index="3">Test</p>
<p class="text" data-index="4">Test</p>
</nav>
<div id="main" class="center">
<svg width="1000" height="200" id="timeline">
<line x1="0" y1="200"
x2="1000" y2="200"
stroke="black"
stroke-width="4"/>
</svg>
</div>
JavaScript
$(".text").click(function(event) {
var index = $(event.target).data("index");
switch(index) {
case "0":
$("#timeline").hide("slow");
break;
case "1":
$("#timeline").show("slow");
break;
}
});
Here is a JSFiddle demonstrating a full example: https://jsfiddle.net/James_Parsons/s0gze1qq/1/
Upvotes: 2
Views: 96
Reputation: 3305
from
var index = $(event.target).data("index");
to
var index = $(this).data("index");
JS code will like this,
$(".text").click(function(event) {
var index = $(this).data("index");
switch(index) {
case "0":
$("#timeline").hide("slow");
break;
case "1":
$("#timeline").show("slow");
break;
}
});
Upvotes: 1
Reputation: 6608
Issue is in the way you're doing the switch case.
var index = $(event.target).data("index");
This returns a number not a string value, so change your switch case like below and it will work.
switch(index) {
case 0:
$("#timeline").hide("slow");
break;
case 1:
$("#timeline").show("slow");
break;
}
Here's a Fiddle fork with updated changes :)
Upvotes: 1
Reputation: 240928
The indices are numbers, not strings, therefore you should use:
Updated Example - (as a side note, you weren't including jQuery)
$(".text").click(function(event) {
var index = $(event.target).data("index");
switch(index) {
case 0:
$("#timeline").hide("slow");
break;
case 1:
$("#timeline").show("slow");
break;
}
});
Upvotes: 1