Very simple jQuery spoiler function works half way

I have implemented a really simple jQuery spoiler functionality using the following code:

HTML:

<a href="" onclick="return false" class="spoiler" content="spoiled content">
    Reveal spoiler
</a>

      


jQuery / Javascript:

$('a.spoiler').click(function(){
    $text = "<a href=\"\" onclick=\"return false\" class=\"spoiler\" content=\"" + $(this).text() + "\">" + $(this).attr("content") + "</a>"; 
    $(this).replaceWith($text);
});

      


Basically, I just want the spoiler content attribute to be replaced with the text between the tags. It works for the first click, however when pressed again, it doesn't switch back.

Is there any way for me to implement this in a way where it will replace content indefinitely?

Thank!

+3


source to share


4 answers


Just use

$('a.spoiler').click(function(){
    var text = $(this).text(); 
    var content = $(this).attr("content");
    $(this).text(content).attr("content", text)
});

      

DEMO



Otherwise, you need to use Event Delegation with .on () , as you are using replaceWith

which removes the element that the event was bound to.

$(document).on('click','a.spoiler',function(){
    $text = "<a href=\"\" onclick=\"return false\" class=\"spoiler\" content=\"" + $(this).text() + "\">" + $(this).attr("content") + "</a>"; 
    $(this).replaceWith($text);
});

      

DEMO

+3


source


You can use this

$('a.spoiler').click(function () {
    $(this).text(function (_, t) {
        return t.trim() == "Reveal spoiler" ? $(this).attr('content') : "Reveal spoiler";
    });
});

      



DEMO

+2


source


Change your code to

$(document).on('click','a.spoiler',function(){
    $text = "<a href=\"\" onclick=\"return false\" class=\"spoiler\" content=\"" + $(this).text() + "\">" + $(this).attr("content") + "</a>"; 
    $(this).replaceWith($text);
});

      

If new HTML is injected into the page, use delegated events to attach an event handler

Edit -

DEMO

+1


source


$('a.spoiler').click(function(){
    $text =  $(this).attr("content")
    $(this).attr("content",$(this).text()).text($text);
});

      

0


source







All Articles