0

I've pieced together the following jQuery to make an accordion effect work. This works...

$("#FAQs .answer").hide();
$("#FAQs .close").hide();
$("#FAQs .open").show();

// Click the #Expand button to show and hide .answer
$('#Expand').click(function() {

if ($(this).text() === 'Minimise FAQs') {
    $(this).text('Expand FAQs');
    $('#FAQs .answer').slideUp('fast');
    $("#FAQs .close").hide();
    $("#FAQs .open").show();

} else {
    $(this).text('Minimise FAQs');
    $('#FAQs .answer').slideDown('fast');
    $("#FAQs .close").show();
    $("#FAQs .open").hide();

}
});

// Click the Quesiton (h2) to show and hide the answer
$("#FAQs h2").addClass("link").click(function() {
$(this).parent().children(".answer").slideToggle('fast');
$(this).parent('li').children(".close").toggle();
$(this).parent('li').children(".open").toggle();
});

This code (above) makes the following HTML open and close all the accordions on the page:

<section class="row m_b_zero">
<div class="inner-container">
    <div class="box">
        <div class="box-inner"> <div class="faq-controls">
            <span id="Expand">Expand FAQs</span>
        </div></div>
    </div>
</div>
</section>

This still works great.

However.

I need to inject that HTML into the page using jQuery, so I scraped this together:

$(function() {
$( 'section:nth-child(2)' ).after( '<section class="row m_b_zero"><div class="inner-        container"><div class="box"><div class="box-inner"><div class="faq-controls"><span id="Expand">Expand FAQs</span></div></div></div></div></section>' );
});

This injects the same accordion controller HTML as before after the second <section> tag.

This almost works.

The HTML is injected as expected but the button doesn't work? It doesn't open and close the accordion.

I've made sure this jQuery is placed after the jQuery controlling the accordion and it's inside a page ready function.

Anyone know why it wouldn't work?

StephenMeehan
  • 1,083
  • 2
  • 15
  • 26

2 Answers2

1

You are giving the same id to two different elements. When you use an id selector in jQuery, it returns only the first element with that id. You should use classes instead:

//HTML
<span class="Expand">Expand FAQs</span>

//JS
$('.Expand').click(function() {

Also, if you are dynamically adding them to the page, you should consider event delegation:

$(document).on("click", '.Expand', function() {
Stryner
  • 7,288
  • 3
  • 18
  • 18
0
  • Multiple elements in a document can't have the same id (it's invalid). You should use a class name instead.

  • You should delegate the event handlers for dynamically added elements. assuming you're using class Expand, you can use on() to delegate the event handler as follows:

    $(document).on("click",".Expand", function() {
       // code
    });
    

document is for demo purpose only, It's better to use the closest static ancestor

T J
  • 42,762
  • 13
  • 83
  • 138