Friday, October 14, 2011

jQuery :contains with the exact same value

The task to do:
During my work I had to create a page scrolling effect with a dropdown menu and a (verticaly) very long content. So when someone clicks on a menu item the page has to scroll to the exact position where the content begins.

The idea of the solution:
As the menu-items' text and the title of the content parts are exactly the same, the idea is to find the title tag according to it's content. Then get the Y coordinate of it and scroll the body to this position.

The solution in jQuery:
My first (key) idea was to use jQuery's built-in ":contains" method:
jQuery("h2:contains('Some Value')")

But in this case this won't work perfectly, because there were menu items like "Product" and "Product 2.0". So I needed a ":contains" solution but with the exact values. This is what I came up with:
jQuery("#menu a")
  // disable links. We need only Javascript behavior
  .attr("href", "javascript:void(null)")
  // what shall happen if the link is clicked
  .click(function () {
   // get the text of the menu item
   var text = jQuery(this).text();
   // get the DOM object of the target title (The h2 element wich contains the exact same text of the menu item)
   var target = jQuery('h2').filter(function() {
        return jQuery(this).text() === text;
   });
   // get the position of the target element
   var pos = target.offset();
   // if the position is found...
   if (typeof pos.top != 'undefined') {
    // scroll the page there
    jQuery.scrollTo((pos.top-10) + "px", 700);
   }

  });



Note: I used Ariel Flesler's ScrollTo jQuery plugin. (Thanks Ariel by the way..)

No comments:

Post a Comment