Fork me on GitHub

Hello my name is Pui, I am a web developer based in London.

jQuery - Replicate .toggle(), first and second click, and toggle text

1 May 2014

Problem

​Sometimes just using:

$(this).toggle();

doesn’t quite cut it. And you want to get into that second click to manipulate something differently to the first click, as opposed to just toggling a particular element.What we want to manipulate in this instance, is the text, which we cannot do if we use .toggle()

Solution

I use this solution a lot for accordion type functionalities. So the markup for this particular solution is as so:

<span class="nav-plus-minus" role="presentation">+</span> <ul>   <li>A list item</li> </ul>

So we will attach the click event to the span. And the element you are toggling is the <ul>. We use :visible in order to tell if the element is visible on screen. If it isn’t we then do something else.

With regards to toggling text we use text == “+” ? “-” : “+” which means that if the text equals + than change text to -, else have it as +.

$('.nav-plus-minus').click(function(){  if( $(this).siblings('ul').is(':visible') ) {    //First click    $(this).siblings('ul').hide();    var text = $(this).text();    $(this).text( text == "+" ? "-" : "+" );  } else {    //Second click    $(this).siblings('ul').show();    var text = $(this).text();    $(this).text( text == "-" ? "+" : "-" );  } });

About the author

Pui-Ling Lau, front end web developer and designer based in Kent and London

Pui is a User Experience developer working as a contractor in and around London.