Page 1 of 1

FIX for hash# links with jQuery plugin - linking to homepage

Posted: Tue Sep 24, 2013 7:38 am
by Simon66
So I'm busy using a ThemeForest theme - best $15 ever spent. You get an Aladdins Cave of html/css/jQuery and somebody else has already figured out the hard stuff.

This theme comes with a filterable gallery using the jQuery plugin Masonry and a custom filter script. I've created an instance in ListIt2 and built my summary template with this category template included/embedded:

Code: Select all

<!-- categories -->
<section class="filter">
    <a href="#">all</a>
{foreach from=$categories item=category}
    <a href="#{$category->name}">{$category->name}</a>
{/foreach}
</section>
<!-- categories //-->
Both templates are based on the code from the Themeforest theme which has a masonry gallery that works perfectly.

But when I try it in CMSms the hash in each filter link causes the page to redirect to the homepage. I know this is a default behavior in CMSms so I started searching for a workaround and found this online:

Code: Select all

<__script__ type="text/javascript">
/* <![CDATA[ */
( function( $ ) {
   $( 'a[href="#"]' ).click( function(e) {
      e.preventDefault();
   } );
} )( jQuery );
/* ]]> */
</__script>
Only problem was to figure out how to put this somewhere useful.
I narrowed it down to this bit of code in the custom Jquery filter:

Code: Select all

		$('.filter').each(function() {
			var links = $('> a', this);
			var items = $(this).next('.items');
			links.click(function() {
				var category = $(this).attr('href').substr(1);
				if (category == '') {
					$('.item', items).removeClass('hidden').fadeIn(250);
				} else { Yadda, Yadda
}
And I changed it to this:

Code: Select all

		$('.filter').each(function() {
			var links = $('> a', this);
			var items = $(this).next('.items');
			links.click(function(e) {
				e.preventDefault();
				var category = $(this).attr('href').substr(1);
				if (category == '') {
					$('.item', items).removeClass('hidden').fadeIn(250);
				} else { Yadda, Yadda
}
Adding the e.preventDefault to the click function.

The filter worked perfectly and the hash links work as expected.

Simon66