user2252219 user2252219 - 2 months ago 9
HTML Question

FadeToggle change text and show

I'm trying to get a fade toggle to work. When you click on (+) two it is supposed to show two links and change to (-) two and when you press again it closes those links and goes back to (+) two. Right now, I can't get anything to happen when you press on the toggle.

<div id="ending">
An everyday snapshot of
<div class="toggle"><span style="font-size:11px">(+) </span>two </div> sfsfs



</div>

<div class="content">
<a href="http://sfs.co.nz/" target="_blank">sfs</a> & <a href="http://sfsfs.co.nz/" target="_blank">sfsf</a>

</div>


$(document).ready(function() {
$(".content").hide();
$(".toggle").on("click", function() {
var txt = $(".content").is(':visible') ? '(+) two' : '(-) two';
$(".toggle").text(txt);
$(".toggle").toggleClass('active');
$(this).next('.content').slideToggle(450);
e.stopPropagation();
});
});


https://jsfiddle.net/Dar_T/b5tbfn5g/

Answer

1) You actually have to reference/include the jQuery library for jQuery functions to work.

2) You had an improper selector.

  • Rather than $(this).next('.content').slideToggle(450);
    just use $('.content').slideToggle(450); or
    $(this).parent().next('.content').slideToggle(450);

The content div is not a sibling of the toggle div.. so next() isn't going to find it. But if you back up to the parent of the toggle div, then the content div is a sibling, so next() will find it.....

Depending on the rest of the markup, the selector may need to be further altered, but that's the main issue with the function overall.

Seems to work with the selector fixed and the jQuery library actually included.

 $(document).ready(function() {
      $(".content").hide();
      $(".toggle").on("click", function() {
        var txt = $(".content").is(':visible') ? '(+) two' : '(-) two';
        $(".toggle").text(txt);
        $(".toggle").toggleClass('active');
        $(this).parent().next('.content').slideToggle(450);
        e.stopPropagation();
      });
    });

Updated Fiddle