Frontendplace Blog

Sharing Frontend developing ideas

  • Adds

Archive for June, 2009

Adding More and less links on article with jQuery example

Posted by info on 6th June 2009

Here is an example how to add a more and less link to an article list in an unobtrusive way with jQuery.



(function($)
{
	$.fn.setMoreLess = function()
	{
		return this.each(function()
		{
			var $article = $(this);
			// get the link in the heading
			var $articleLink = $article.find('>h3 a');
			// get first paragraph
			var $firstParagraph = $article.find('p:first');
			// get element to show when more is pressed
			var $more = $article.find('.more');

			// hide related article based on the hash of the link
			$articleLink.find(this.hash).hide().end()
				// add click event to toggle article
				.click(function($e)
				{
					$e.preventDefault();
					$(this.hash).toggle();
				})
				// initial hide
				.click();

			// add more and less links on paragraphs
			$firstParagraph.append('<a class="actionLink" title="more" href="#">More</a>')
			.end()

			// append less link to .more element
			$more.append('<a class="actionLink" title="less" href="#">Less</a>').hide()
			.end()

			// add eventhandlers on added links
			$firstParagraph.find('a.actionLink[title=more]')
							.click(function($e)
							{
								$e.preventDefault();
								var $more_link = $(this);
								// hide more link
								$more_link.hide();

								// show more
								$more.show()
									// find less link
									.find('a.actionLink[title=less]')
										// add click event on less link
										.click(function($e)
										{
											// show more link again
											$more_link.show();
											// hide parent
											$more.hide();
										}); // end click less

							}); // end click more
		}); // end each
	}//end function setMoreLess

	// add moreless click events on ready
	$(function()
	{
		 $('.ct_uitgebreidArtikel').setMoreLess();
	});

})(jQuery)

Posted in Scripting | No Comments »