Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery toggle text on click

Tags:

jquery

I have been trying to solve this, i succeeded somewhat but i'm stuck now.

I have this structure:

<h4>title</h4>
<p>text</p>
<hr />
<h4>title</h4>
<p>text</p>
<p>text</p>
<hr />
<h4>title</h4>
<p>text</p>
<hr />

What i'm basically trying to accomplish is to toggle the words tonen (meaning open) and verbergen (meaning hide) when slidding the P's up and down. At the moment i append a span with the word tonen and check wether its shown or not.

The content is hidden on load, tonen is shown, but when h4 is clicked, the content is shown but tonen won't change to verbergen. I have read about live and on but don't get it.

<script>
    $(function(){
    $("h4").append("<span> - tonen</span>");
    $("h4").nextUntil("hr").hide();
    $("h4").click(function () {
        $(this).nextUntil("hr").slideToggle("fast");
        if(span.text() == " - tonen"){
            span.text(" - verbergen");
        } else {
            span.text(" - tonen");
        }
    });
    });
</script>
like image 660
Tessed Avatar asked Mar 25 '23 02:03

Tessed


2 Answers

You just need to get text of your current child span of clicked h4 and change to opposite text based on retrieved span's text:

$("h4").click(function () {
    $(this).nextUntil("hr").slideToggle("fast");
    var text = $(this).find('span').text();
    $(this).find('span').text(text == " - verbergen " ? " - tonen " : " - verbergen ");
});

Updated Fiddle

like image 76
Eli Avatar answered Mar 26 '23 15:03

Eli


LIVE DEMO 1

$("h4").append(" - <span>tonen</span>").click(function() {
    var $sp = $('span', this);
    $(this).nextUntil("hr").slideToggle("fast");
    $sp.text( $sp.text()=="tonen"?"verbergen":"tonen");
}).nextUntil("hr").hide();

LIVE DEMO 2

$("h4").append(" - <span>tonen</span><span style='display:none;'>verbergen</span>").click(function() {
     $(this).nextUntil("hr").slideToggle(400).end().find('span').toggle();
}).nextUntil("hr").hide();
like image 20
Roko C. Buljan Avatar answered Mar 26 '23 17:03

Roko C. Buljan