Scroll to div on link click - javascript

There are questions all over SO about this topic, but I've tried a ton of different scripts for this and I cannot get it to work with my site.
I am building a personal portfolio wordpress theme for myself, and would like to keep it a one page theme. What I want is when a user clicks a link on the navigation, the page scrolls down to that section. Easy right? No.
I don't know why it isn't working on my site, but I think it has to do with the script I am using for the scroll to fixed navigation.
Here is the script I am currently attempting to use to create this in-page navigation scrolling effect: http://css-tricks.com/snippets/jquery/smooth-scrolling/
And here is the script I am using to create the scroll to fixed navigation effect:
window.onscroll=function () {
var top = window.pageXOffset ? window.pageXOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
if(top > 640){
document.getElementById("nav").style.position = "fixed";
document.getElementById("nav").style.height="65px";
} else {
document.getElementById("nav").style.position = "relative";
document.getElementById("nav").style.height="65px";
}
}
You can view the site I am trying to do this on at http://www.tylerb.me
Are the two scripts contradicting each other and making one of them not work?

It would appear wordpress uses the jQuery.noConflict() method to prevent well.. conflicts from occurring. Because of the script conflicts(moo tools uses $ as well, for example), replace each $ with jQuery. This should fix your issue.. and I do mean in the code which calls the plugin, not the plugin itself.
Example:
//normal jquery method call:
$("element").method(etc);
//with noConflict code:
jQuery("element").method(etc);
UPDATE 1:
It would appear that you forgot to leave a particular $ alone. This line:
var target = jQuery(this.hash), target = this.hash;
Should be this:
var $target = jQuery(this.hash), target = this.hash;
This of course goes with any variable that begins with a $. Those ones should not be deleted.

The core of your issue is that jQuery is not loading.
Daedalus just got there before me. It's no conflict that's causing your issue. Just use jQuery rather than $.

This could prove useful to some.
Try using:
jQuery(document).ready(function($){
// do stuff here using $
});
instead of
$(document).ready(function($){
// do stuff here
});
This declares a local $ instead of conflicting with the previously declared.
It helped me lots of times.

Related

My Script is not working in wordpress static site

I am working on my wordpress site, and i use a static page for my front/home page. I wanted to use parallax scrolling but i cant get my script to load and work.
I linked it in header like this:
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/js/scroll.js"></script>
and this is my scroll script:
(function($) {
$.fn.parallax = function(options) {
var windowHeight = $(window).height();
// Establish default settings
var settings = $.extend({
speed: 0.15
}, options);
// Iterate over each object in collection
return this.each( function() {
// Save a reference to the element
var $this = $(this);
// Set up Scroll Handler
$(document).scroll(function(){
var scrollTop = $(window).scrollTop();
var offset = $this.offset().top;
var height = $this.outerHeight();
// Check if above or below viewport
if (offset + height <= scrollTop || offset >= scrollTop + windowHeight) {
return;
}
var yBgPosition = Math.round((offset - scrollTop) * settings.speed);
// Apply the Y Background Position to Set the Parallax Effect
$this.css('background-position', 'center ' + yBgPosition + 'px');
});
});
}
}(jQuery));
$('.parallax-section-1').parallax({
speed : 0.15
});
I found some articles that i would have to use the functions.php and enque the script but i never did that before so im a bit lost, so any help would be highly appreciated.
First things first, lets load the script the "WordPress Way". This will actually help simplify troubleshooting.
To do that, edit your theme's functions.php file.
In that file, add this PHP code. Be sure it is between <?php opening / closing tags.
Typically, I'd recommend adding it to the end of the file, but if your file includes this ?> - that the code you add is before the ?>:
add_action('enqueue_scripts', 'my_custom_script');
function my_custom_script() {
// Be sure jQuery is loading
wp_enqueue_script('jquery');
// Load your script
wp_enqueue_script('my-parallax-script', get_template_directory_uri() . '/js/scroll.js', array('jquery'), FALSE, TRUE);
}
Now - once you do this, you will want to be sure that your script is in fact loading. To do that, visit the page, then do a VIEW SOURCE in your browser. When you view source, do a search of the code for "scroll.js" - if you find it, great. Click on the url (or copy / paste it into your browser window) and be sure that the script is referencing the right location. If not, you'll need to be sure to move the script to the right location, so the page will load it.
Next Step
You have a problem with your script that will not work in WordPress. You are referencing jQuery with the $ symbol, AND it appears that you are referencing an element directly, which means there's a good chance the element doesn't exist when the script will run, which means that it won't have the desired effect.
Instead, we need to do two things. Because WordPress loads jQuery in what's called no conflict mode, you need to reference it using jQuery, not $. AND you need to put your code into a document ready function.
Thankfully, jQuery offers a slick way of doing the document ready that exposes the $ inside of the document ready, for convenience:
// Shorthand version of "No-conflict-safe" document ready
jQuery(function($) {
// Inside here, we can use $ instead of jQuery
$('.parallax-section-1').parallax({
speed : 0.15
});
});
If it still does not work after all of this, then you need to open your console in your browser, and look for any javascript errors. They will help you identify what is going on, which is the first step to solving the problem.

Going to a page anchor after load adding transition

I'm quite new at using jquery but learning a bit everyday. I have solved many problems searching this web but I can't seem to find any solution for this one:
The web I'm workign at the moment use quite a lot of page anchors.
I have localscroll and scrollto as jquery libraries.
I animated the transition with this little script:
<script type="text/javascript">
$(document).ready(function () {
$('.scrolllento').localScroll({ duration: 1000 });
});
</script>
and it works fine whatever I add the class "scrolllento" to the cointainer of my links.
Now the problem I have is when a link jumps to an anchor of inside different page. my client has asked me if it's possible to load the page first then move to the anchor with same web transition.
I have been working on it with my little knowdlege and this is what I have atm:
<script type="text/javascript">
$(document).ready(function () {
var nosalto = $(location).attr('href');
if (nosalto.indexOf("HistoriaBMG") > 0) {
$.fn.gotoAnchor = function (anchor) {
location.href = this.selector;
}
$('#historia').gotoAnchor();
}
});
</script>
"HistoriaBMG" is the new page and "#historia" is the anchor I want to go inside that page.
and it seems again that it works...
the problem is I have no idea how to implement now the transition as the class "scrolllento" in the container of the link going to ../HistoriaBMG is ignored.
could anyone help me? thanks so much in advance and excuse my english, hope this question is clear enough.
According to the localScroll docs:
The plugin also adds a function, $.localScroll.hash() , that checks the URL in the address bar, and if there's a hash(#an_id), it will scroll to the element. It accepts a hash of settings, just like $.localScroll. You will likely call it on document ready. Check the regular example to see it in action.
So you simply need to call $.localScroll.hash()on $(document).ready()

Scroll to reveal content jQuery Plugin

I am in need a cross-browser jQuery solution for revealing elements on a HTML page with jQuery, the elements are loaded on page load, however i want to have the ability to scroll the page to "fadein" elements.
Is there an existing plugin with this functionality ?
NOTE: loading of the data is not required, and google has failed me thus far.
$(window).scroll(function(){
if ($(document).height() - $(window).height() < 20)
{
var content = 'hi'; //you can use a AJAX call to get content
$('#DivToAppendContentTo').append('content');
}
});
I've used this in the past. Read over and see if it works for you. There is a Demo at the bottom and you'll need to modify the code slightly to add your fade in. Be sure to give your element a CSS style of Hidden so that it is first not seen on the page. The jQuery fade in function will take display it.
Ariel Flesler's ScrollTo:
http://flesler.blogspot.com/2007/10/jqueryscrollto.html
Here you go, a plugin can do that easily!
http://scrollrevealjs.org/

How can I scroll to a page element in jQuery Mobile?

I have a long jQuery mobile page and would like to scroll to an element halfway down this page after the page loads.
So far I've tried a few things, the most successful being:
jQuery(document).bind("mobileinit", function() {
var target;
// if there's an element with id 'current_user'
if ($("#current_user").length > 0) {
// find this element's offset position
target = $("#current_user").get(0).offsetTop;
// scroll the page to that position
return $.mobile.silentScroll(target);
}
});
This works but then the page position is reset when the DOM is fully loaded. Can anyone suggest a better approach?
Thanks
A bit late, but I think I have a reliable solution with no need for setTimeout(). After a quick look into the code, it seems that JQM 1.2.0 issues a silentScroll(0) on window.load for chromeless viewport on iOS. See jquery.mobile-1.2.0.js, line 9145:
// window load event
// hide iOS browser chrome on load
$window.load( $.mobile.silentScroll );
What happens is that this conflicts with applicative calls to silentScroll(). Called too early, the framework scrolls back to top. Called too late, the UI flashes.
The solution is to bind a one-shot handler to the 'silentscroll' event that calls window.scrollTo() directly (silentScroll() is little more than an asynchronous window.scrollTo() anyway). That way, we capture the first JQM-issued silentScroll(0) and scroll to our position immediately.
For example, here is the code I use for deep linking to named elements (be sure to disable ajax load on inbound links with data-ajax="false"). Known anchor names are #unread and #p<ID>. The header is fixed and uses the #header ID.
$(document).bind('pageshow',function(e) {
var $anchor;
console.log("location.hash="+location.hash);
if (location.hash == "#unread" || location.hash.substr(0,2) == "#p") {
// Use anchor name as ID for the element to scroll to.
$anchor = $(location.hash);
}
if ($anchor) {
// Get y pos of anchor element.
var pos = $anchor.offset().top;
// Our header is fixed so offset pos by height.
pos -= $('#header').outerHeight();
// Don't use silentScroll() as it interferes with the automatic
// silentScroll(0) call done by JQM on page load. Instead, register
// a one-shot 'silentscroll' handler that performs a plain
// window.scrollTo() afterward.
$(document).bind('silentscroll',function(e,data) {
$(this).unbind(e);
window.scrollTo(0, pos);
});
}
});
No more UI flashes, and it seems to work reliably.
The event you're looking for is "pageshow".
I was digging a lot this issue, also at jQuery mobile official forum.
Currently it seems that there is no solution (at least for me).
I tried different events (mobileinit, pageshow) and different functions (silentscroll, scrolltop) as suggested above, but, as a result, I always have page scrolled until all images and html is finished loading, when page is scrolled to top again!
Partial and not really efficient solution is using a timer as suggested in comment to sgliser's answer; unfortunately with a timeout is difficult to know when page will be fully loaded and if scroll happened before that, it will scroll back to top at the end of load, while if it happens too long after page has fully loaded, the user is already scrolling page manually, and further automated scroll will create confusion.
Additionally, would be useful to have silentscroll or other function to address a specific id or class and not plain pixels, because with different browsers, resolutions and devices it may give different and not correct positioning of the scroll.
Hope someone will find a smarter and more efficient solution than this.

Prevent/stop auto anchor link from occurring

I need to prevent the automatic scroll-to behavior in the browser when using link.html#idX and <div id="idX"/>.
The problem I am trying to solve is where I'm trying to do a custom scroll-to functionality on page load by detecting the anchor in the url, but so far have not been able to prevent the automatic scrolling functionality (specifically in Firefox).
Any ideas? I have tried preventDefault() on the $(window).load() handler, which did not seem to work.
Let me reiterate this is for links that are not clicked within the page that scrolls; it is for links that scroll on page load. Think of clicking on a link from another website with an #anchor in the link. What prevents that autoscroll to the id?
Everyone understand I'm not looking for a workaround; I need to know if (and how) it's possible to prevent autoscrolling to #anchors on page load.
NOTE
This isn't really an answer to the question, just a simple race-condition-style kluge.
Use jQuery's scrollTo plugin to scroll back to the top of the page, then reanimate the scroll using something custom. If the browser/computer is quick enough, there's no "flash" on the page.
I feel dirty just suggesting this...
$(document).ready(function(){
// fix the url#id scrollto "effect" (that can't be
// aborted apparently in FF), by scrolling back
// to the top of the page.
$.scrollTo('body',0);
otherAnimateStuffHappensNow();
});
Credit goes to wombleton for pointing it out. Thanks!
This seems the only option I can see with ids:
$(document).ready(function() {
$.scrollTo('0px');
});
It doesn't automatically scroll to classes.
So if you identify your divs with unique classes you will lose a bit of speed with looking up elements but gain the behaviour you're after.
(Thanks, by the way, for pointing out the scroll-to-id feature! Never knew it existed.)
EDIT:
I know this is an old thread but i found something without the need to scroll. Run this first before any other scripts. It puts an anchor before the first element on the page that prevents the scroll because it is on top of the page.
function getAnchor(sUrl)
{
if( typeof sUrl == 'string' )
{
var i = sUrl.indexOf( '#' );
if( i >= 0 )
{ return sUrl.substr( i+1 ).replace(/ /g, ''); }
}
return '';
};
var s = getAnchor(window.location.href);
if( s.length > 0 )
{ $('<a name="'+s+'"/>').insertBefore($('body').first()); }
Cheers!
Erwin Haantjes
Scroll first to top (fast, no effects pls), and then call your scroll function. (I know its not so pretty)
or just use a prefix
This worked well for me:
1- put this on your css file
a[name] { position: absolute; top: 0px }
2- put this on your document.ready bind right before you start animating (if you're animating at all)
$("a[name]").css("position","relative");
Might need tweaking depending on your stylesheet/code but you get the idea.
Credit to: http://cssbeauty.com/skillshare/discussion/1882/disable-anchor-jump/

Categories

Resources