Change span text by clicking

Asked

Viewed 100 times

0

I created this function so that when it was clicked, show posts' tags. It works normally but I would like to change the text "open tags" to "Hide tags" when it was clicked, how do I do this?

$(document).ready(function() {
    $(".notec").click(function(){
        $(".t").slideToggle();
    });
});
.t{display: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tags">
                        	
    <span class="notec">open tags</span>

    <div class="t">
        <a href="/">tag 1</a>
        <a href="/">tag 2</a>
        <a href="/">tag 3</a>
    </div>
    
</div>

1 answer

1


Hi. You can get the text that is appearing on span using $(this).text() within the event of click. Then just check if the value of the text is "open tags" or "hide tags" and change. To change the text just use $(this).text("Novo Texto").

Follow the working code:

$(document).ready(function() {
    $(".notec").click(function(){
        $(".t").slideToggle();
        var text = $(this).text();
        if (text == "open tags") {
          $(this).text("hide tags");
        } else {
          $(this).text("open tags");
        }
    });
});
.t{display: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tags">
                        	
    <span class="notec">open tags</span>

    <div class="t">
        <a href="/">tag 1</a>
        <a href="/">tag 2</a>
        <a href="/">tag 3</a>
    </div>
    
</div>

I hope I’ve helped.

  • You’ve been very helpful, thank you!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.