Jquery - combine code into a common function

Hi,

Now I know this should be very simple … but for the life of me I can’t think how to do it.

Here’s the problem … I’ve got text two elements on a page that, when clicked, toggle separate content so that it either shows or hides it. When these items are clicked, I want to check the vale if the text and, if it’s ‘Show’ then I want to change it to ‘Hide’ and vice versa.

I’ve got some Jquery code that’s working but, I seem to have written the same code twice - once for each function.

anyone tell me how to combine the common code into one simple function that will change the ‘clicked’ text to wither ‘show’ or ‘hide’

$(document).ready(function()
{
	
	$('.show').click(function()
		{
			var target = 'comments-'+$(this).attr("id");
			var text=$(this).text();
			var n=text.indexOf("show");
			$('#' + target).slideToggle('slow');
			if (n > -1)
				{
					newtext=text.replace("show","hide");
				}
			else	
				{
					newtext=text.replace("hide","show");
				}
			$(this).text(newtext);	
		});
		


	$('.showpost').click(function()
		{
			var thisid = $(this).attr("id");
			var splitx=thisid.split("-");
			var target='content-'+splitx[1];
			var text=$(this).text();
			var n=text.indexOf("show");
			$('#' + target).slideToggle('slow');
			if (n > -1)
				{
					newtext=text.replace("show","hide");
				}
			else	
				{
					newtext=text.replace("hide","show");
				}
			$(this).text(newtext);
		});


}); 

Hi there,

You could do something like this:

function toggleText(text){
  return (text == "show")? "hide" : "show"
}

Then:

$('.show').click(function() 
  var target = 'comments-'+$(this).attr("id");
  var buttonText = $(this).text();
  $('#' + target).slideToggle('slow');
  $(this).text(toggleText(buttonText));	
});

I changed the variable “text” to “buttonText” (or whatever), so as to not confuse it with the method text()
Also, I didn’t test this code, so if it doesn’t work as expected, just let me know and I’ll have a closer look.

HTH

That idea worked perfectly - thanks!

Cool! :slight_smile:
Thanks for taking the time to follow up!