How can I add link-specific scrolling animations, horizontal and vertical, using jQuery?
Question
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 div
s up and down etc. but I want the div
s 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
Solution
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).
OTHER TIPS
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">foo2</a>
</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
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(...);