views:

146

answers:

3

I've got this script on my website:

$(document).ready(function() {
  function filterPath(string) {
    return string
      .replace(/^\//,'')
      .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
      .replace(/\/$/,'');
  }

  $('[href*=#]').each(function() {
    if ( (filterPath(location.pathname) == filterPath(this.pathname))
      && (location.hostname == this.hostname)
      && (this.hash.replace(/#/,'')) ) {

      var $targetId = $(this.hash), 
        $targetAnchor = $('[name=' + this.hash.slice(1) +']');
      var $target = $targetId.length 
        ? $targetId 
        : $targetAnchor.length ? $targetAnchor : false;
      if ($target) {

        var divOffset = $target.parent().offset().top;
        var pOffset = $target.offset().top;
        var pScroll = pOffset - divOffset;

        $(this).click(function() {
          $target.parent().animate({scrollTop: pScroll + 'px'}, 600);
          return false;
        });
      }
    }
  }); 
});

It works well, and scrolls the main nav divs up and down etc. but I want the divs inside the services section to scroll left and right. I also want to add a slider to the portfolio section but the above code over rules any additional code as it's applied to all <a href...> tags. How do I only specify it to the mainnav ul?

thanks in advance

A: 

Suppose you have the following structure and you want to apply a function only to the "foo" link. And leave all other untouched.

<div id="mainnav">
  <ul>
    <li>
      <a href="#">foo</a>
    </li>
    <li>
      <a href="http://www.example.com"&gt;foo2&lt;/a&gt;
    </li>
  </ul>
  <ul>
    <li>
      <a href="#">foo3</a>
    </li>
  </ul>
  <a href="#">foobar</a>
</div>

Then you could use such a jQuery selection

$("#mainnav > ul:first").find("a[href*=#]").css('color','red');

Broken into pieces

$("#mainnav > ul:first")
//give me the element with id mainnav and then the first ul child element of it

.find("a[href*=#]")
//find all link elements in this ul which have href set to #

.css('color','red');
//and set their color to red
jitter
+1  A: 

Change the selector from '[href*=#]' to 'ul.mainnav [href*=#]'.

How to write selectors which just give you the elements you want is probably the most important thing to know when using jQuery. I can only recommend reading the fine jQuery documentation on selectors (but the other stuff is recommended too).

Simon Lehmann
A: 

I'm not sure I understand your question exactly, but if you're looking for a way to find links only in a certain element, you can expand your selector:

// Assuming your mainnav ul has id="mainnav"
$('ul#mainnav [href*=#]').each(...);

That is mostly a temporary fix if you ask me, however. Sooner or later you might want to apply your effect to other elements. You could add a class attribute for the elements you want the effect on:

<a href="#" class="scroll-effect">...</a>

Then select them like so:

$('.scroll-effect').each(...);
Blixt