Two different anchors to expand/collapse the same div

501 views Asked by At

I have written a code that expands a div when an anchor is clicked. I want to add another anchor that expands the same div when clicked but when I add the second anchor the first one doesn't work. Is it possible that two different anchors can be used to expand the same div? If so, how can I do that? Here is the code that I have written so far:

<div class="Style10" id="ED">

      <h5><a href="#" id="EDA" onclick="Anchor(id)">Education</a><img id="EDI" class="Triangle" src="TriangleDown.png"></h5>

      <div>

           <h6><a href="#" id="EDAA" onclick="Anchor(id)">Add</a></h6>
           //Here I want to add the second anchor that also expands div class="Style11"
           <div class="Style11">
              ....
              some code here
              ....
           <div>

      <div>
<div>

The JQuery code is:

$(document).ready(function(){

   $('#ED div').hide();

   $('#ED a').click(function(e){
        $(this).parent().next('#ED div').slideToggle('normal');
        $(this).parent().toggleClass('active');
        e.preventDefault();
   });

});      

The Anchor function:

 function Anchor(id) {
    if (id == "EDA") {
        if (document.getElementById("EDI").getAttribute("src") ==    "TriangleDown.png") {
            document.getElementById("EDI").src = "TriangleUp.png";
        }
        else {
           document.getElementById("EDI").src = "TriangleDown.png";
        }
    }
}
1

There are 1 answers

1
Artur Filipiak On BEST ANSWER

next() reffers to the closest next element. In your case (when you add another link), for the first link next will be the second link.

You could simply fix that using nextAll() instead of next()

// instead of:
// $(this).parent().next('#ED div').slideToggle('normal');
// this:
$(this).parent().nextAll('div').first().slideToggle('normal');

Also, there's no need to use onclick attribute since you have registered click event handler for the element with jQuery $('#ED a').click(...)

JSFiddle


EDIT

If you have more stuff to handle on click, add it either in click() or onclick method. In this case no need to use both.

JSFiddle 2