-2

I've searched and I found this code so I guess this is the start I should use but I don't really get what attribute is wrong.

<script type="text/javascript">
$("a").click(function (){         
    $(".EventShowID").hide();            
    $("#" + $(this).attr("class")).show().siblings('EventShowID').hide();
});
</script>

Link HTML:

<a href="#EventID1" class="EventID1">EVENT!</a>
<a href="#EventID3" class="EventID3">EVENT!</a>
<a href="#EventID4" class="EventID4">EVENT!</a>

Divs:

<div id="EventShow">
    <div id="EventID1" class="EventShowID">Test Event #1<br>Testing adding an event for fun.</div>              
    <div id="EventID3" class="EventShowID">Test Event #2<br>Testing adding another event for fun.</div> 
    <div id="EventID4" class="EventShowID">Test Event #3<br>Testing adding anotheranother event for fun.</div>
</div>

What is wrong. :(

indiehjaerta
  • 319
  • 1
  • 8
  • 19

2 Answers2

0

Your code needs better structuring:

<a href="#event-1" class="event-toggle">Event 1</a>
<a href="#event-2" class="event-toggle">Event 2</a>

<div class="event" id="event-1">1 here</div>
<div class="event" id="event-2">2 here</div>

jQuery:

$('a.event-toggle').click(function(){
  $('.event').hide();
  var el = $(this).attr('href');
  $(el).show();
});
rybo111
  • 12,240
  • 4
  • 61
  • 70
0

You're not wrapping the click event handler within a jQuery document ready, so it won't be attached properly (jQuery won't find any element before the page is loaded).

Your script should look like this, and be placed after you load the jQuery library:

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        // When the document is ready.
        $(function () {
            // Hide all the elements. This could be replaced by a 
            // CSS rule.
            // ie: 
            // .EventShowID { display: none }
            $(".EventShowID").hide();

            // Attach the click event handler. Use "on" to guarantee it will be 
            // attached to any new element you add dynamically later on.
            $("a.EventToggle").on("click", function () {    
                // Hide all.     
                $(".EventShowID").hide();  

                // Show the element which id is equal the clicked element href.
                $($(this).attr("href")).show();
            });
        });
    </script>
</head>

Demo

emerson.marini
  • 9,331
  • 2
  • 29
  • 46