jquery go to anchor on page load - javascript

i have a WordPress site and problems with anchors. i have a page with several anchors which are linked to in the main menu. when i am on the page itself, all anchors work fine, but if I'am on any other page, they don't work, at least not in all browsers and the anchors are ignored.
As being informed it is a chrome bug, ive found this solution:
<script type="text/javascript">
jQuery(window).load(function(){
var hashNum = 0;
if (window.location.hash != ''){
hashNum = window.location.hash.replace("#oneofmanyanchors", "");
console.log('hashNum: ' + hashNum);
};
hashMenu = jQuery('[data-q_id="#oneofmanyanchors"]').offset().top;
jQuery('html,body').animate({
scrollTop: hashMenu
}, 0);
});
</script>
above code is working and fixes the issues i had in chrome and ff.
however i need this added functionality: At the moment it is addressing only one specific anchor, but i need it to work with any anchors in the page url, not just the one above (anchors are referenced with the data-q_id attribute).
so the code needs to be updated that it grabs any given anchor from the page URL and go to / scroll to that anchor (once) via jquery after first page load.
How do i achieve this?
Thanks in advance!
PS: The problem is caused by theme incompatibility with a certain plugin i need...

I think this should work in every browser - what happens to be the problem?
In order to achieve this in jquery you should scroll to the element/anchor with javascript as soon as the document is loaded.
So like this:
$(function() {
location.hash = "#" + hash;
});
I still think you should find out what went wrong and why the linken from another page doesn't work in some browser before using a workaround for the problem. Your code will just ged more and more messy like that.
How to scroll HTML page to given anchor using jQuery or Javascript?
and here
$(document).ready shorthand

Related

Smooth scrolling to anchor on another page

After combing the forums and how-to guides, I have found a solution to a Smooth Scrolling problem that I had, but I'd like to ask some kind folks if the solution below will work for me before I try it, or if I'm missing something important.
I'm working on a live site and I don't want to create problems or break anything, so I'd like to be sure before I add the code below. I also know nothing about java or coding, so please forgive me if I don't use the right terms.
I want to enable smooth scrolling to an anchor on another page.
e.g. from my home page "domain.com/home", click the link, then
load the new page, e.g. "domain.com/contact"
and on loading the new page, smoothly scroll to the anchor, "domain.com/contact#section1".
Currently, it simply jumps, and I'd like to know if the steps below will enable the smooth scrolling.
I'm planning to:
Add the following codes to the website template's '' section (in the Joomla admin panel):
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js">
</script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
I'm unsure whether this is necessary because I already use jQuery with some components, is it unnecessary to load jQuery again? Or will it not hurt to add this code regardless?
Then add this code to the same section in the template:
<script type="text/javascript" >
$('html').css({
display: 'none'
});
$(document).ready(function() {
var hashURL = location.hash;
if (hashURL != "" && hashURL.length > 1) {
$(window).scrollTop(0);
$('html').css({
display: 'block'
});
smoothScrollTo(hashURL);
} else {
$('html').css({
display: 'block'
});
}
});
function smoothScrollTo(anchor) {
var duration = 5000; //time
var targetY = $(anchor).offset().top;
$("html, body").animate({
"scrollTop": targetY
}, duration, 'easeInOutCubic');
}
</script>
As far as I know, this will enable the smooth scrolling, but I haven't added anything like 'smoothscroll.js' (which I've read a lot about) -- will that also need adding in the '' (after I upload it to the server), or is that included in the jQuery library?
I'm sorry if this seems very naive, I'm learning as I go. Thank you very much in advance to anyone who provides some feedback on this, I am truly grateful for your time and patience.
Best,
Ben
Firstly, Joomla already loads jQuery, so you do not need to load it again. I would either use a Joomla extension (there is a free one here) or use a smooth scroll library (like this one). Assuming you choose to do the latter, you just need to put the link in your Joomla template to the JS file and initialise it (this is all explained on the Github project page).
Both options are simple but if you don't have much experience in coding then the extension is probably the best way to go.
EDIT: To use smoothscroll on page load with the GitHub library, you will need to change your last function to:
function smoothScrollTo(anchor) {
var scroll = new SmoothScroll();
scroll.animateScroll(anchor);
}

.click event work on home page but didn't work and post page

I try to solved this problem but I don't understood where is the error.
I have and footer of all pages a to the visitors can comeback to the important part of the site whit slow animation.
In main page any problem that work correctly.
But in post page the animation didn't existe.
this is an exemple of page with the problem.
the code I used for the animation is this:
$(".gotof").click(function (e) {
var b = $(this).attr("href").substr(1);
console.log(b);
event.preventDefault();
$(".wrapper").animate({
scrollTop: $("#" + b).offset().top + $(".wrapper").scrollTop()-60
}, "slow");
console.log('e');});
First I think is the sibling of the element but no problem in this part.
After I try other functions for scroll to an anchor.
After multiples tests I control if something is not same in the two page but same Js, same plugin.
I don't understand what is the problem.
Please help me.
You're using event.preventDefault() - event is not defined, e is. Change it to e, instead of event, and it'll probably work. If you had looked in the browser console, you'd seen this. That might not be the error, but it will prevent the rest of the script to run.

Script works only on homepage

I have problem with adding class after scroll and it's really strange to me and here is why:
I used this script on multiple projects and never had this problem before. When I scroll down on home page, script works perefectly, class "Fix" is added to class "navigacija" and the social icons, menu and languages are fixed at top of the page. But on other pages this is not the case. Class "Fix" isn't added to class "navigacija" after scrolling 145px down. And what's more interesting, I insert very large image on purpose at this page and until page loads that image, my script works (try to scroll down before image is loaded). When page is fully loaded, script doesn't work anymore. I'm working in Joomla, I made my own template, I didn't install any modules, components or plugins. There are only Joomla's standard js files and my scripts that I used before with this script without any problem.
Here is the website I'm working on: http://investfarm.moderanweb.rs/
and here is the script:
$(function() {
var navigacija = $(".navigacija");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 145) {
navigacija.removeClass('navigacija').addClass("Fix");
} else {
navigacija.removeClass("Fix").addClass('navigacija');
}
});
});
Please help, thanks in advance.
Try to change $ to jQuery if you are using jQueryNoConflict, and why is it working on homepage, I guess because jQuery library is loaded twice, before and after mootools library, so try this instead, and you should do the same for ToolTip and other stuffs :
jQuery(function() {
var navigacija = $(".navigacija");
jQuery(window).scroll(function() {
var scroll = jQuery(window).scrollTop();
if (scroll >= 145) {
navigacija.removeClass('navigacija').addClass("Fix");
} else {
navigacija.removeClass("Fix").addClass('navigacija');
}
});
});
For starters, start cleaning up the errors that show in the console.
You have multiple script tags that points to an HTML page not to a script.
<script type="text/javascript" src="/templates/investfarmimpexmd/js/jquery-2.1.1.js"></script>
<script type="text/javascript" src="/templates/investfarmimpexmd/js/wow.min.js"></script>
<script src="/js/wow.min.js"></script>
I don't know what you expected those to be loading, but it is not loading a script and is causing errors.
Perhaps these be marked type="text/template" so the browser doesn't try to execute them and you can use them as templates?
And, you have an error on this line of inline Javascript that indicates that jQuery is not loaded properly so you will have to find out why that is:
jQuery(window).on('load', function() {
new JCaption('img.caption');
});
And, you are loading multiple different versions of jQuery in the same page, but not managing how those different versions are used. You can't just load a version of jQuery, issue a jQuery.noConflict() and then load another version of jQuery. The first will be doing nothing at that point so if you needed it for something, it will not be working.

Linking within the page

I have seen a lot of websites where they are linking in the same page.
(demo)
The problem in this system is, when you reload the page after clicking the link (which refers you to the selected area), the page immediately scrolled to the selected area, because the click on the link leaves a #name on the URL page (even when reloading), for example:
www.example.com/#down
I have seen also websites, where they don't add #name to the URL line but you still referred to the linked area.
I guessed this has been made by jQuery or Javascript but I couldn't find (inspect element and page's source) the code (I found this system in high-tech sites, where they have a lot of js files and it was complicated to find).
My real question is: how can I link within my website, without using the hash-tag|name system?
The behaviour you describe is the intended, desired behaviour of anchors. As has been said...
Websites aren't broken by default, they are functional, high-performing, and accessible. You break them.
You can have an event listener detect clicks on links and scroll accordingly. jQuery would be something like this:
$(document).on("click", "a[href*='#']", function(evt) {
evt.preventDefault();
var target = this.href.split("#")[1];
var elm = document.getElementById(target);
if( elm) elm.scrollIntoView(); // or replace with fancy scrollTo plugin
});
However, be aware that doing this decreases usability. From xkcd...
Working DEMO
HTML:
GO SEE THE DEMO
jQuery:
$("a").click(function(event) {
event.preventDefault();
var divId = $(this).attr('href');
$('html, body').animate({
scrollTop: $(divId).offset().top
}, 500);
});

How can I tell if a page has jumped to the anchor (#) in JavaScript?

I have some JavaScript that can appear on many different pages. Sometimes those pages have been accessed via a URL containing an anchor reference (#comment-100, for instance). In those cases I want the JavaScript to delay executing until after the window has jumped. Right now I'm just using a delay but that's pretty hackish and obviously doesn't work in all cases. I can't seem to find any sort of DOM event that corresponds to the window "jump".
Aside from the simple delay, the only solution I've come up with is to have the JS look for the anchor in the URL and, if it finds one, watch for changes in scrollTop. But that seems buggy, and I'm not 100% sure that my script will always get fired before the scrolling happens so then it would only run if the user manually scrolled the page. Anyhow, I don't really like the solution and would prefer something more event driven. Any suggestions?
Edit to clarify:
I'm not trying to detect a hash change. Take the following example:
Page index.php contains a link to post.php#comment-1
User clicks the link to post.php#comment-1
post.php#comment-1 loads
$(document).ready fires
Not long later the browser scrolls down to #comment-1
I'm trying to reliably detect when step 5 happens.
You can check window.onhashchange in modern browsers. If you want cross compatible, check out http://benalman.com/projects/jquery-hashchange-plugin/
This page has more info on window.onhashchange as well.
EDIT: You basically replace all anchor names with a similar linking convention, and then use .scrollTo to handle the scrolling:
$(document).ready(function () {
// replace # with #_ in all links containing #
$('a[href*=#]').each(function () {
$(this).attr('href', $(this).attr('href').replace('#', '#_'));
});
// scrollTo if #_ found
hashname = window.location.hash.replace('#_', '');
// find element to scroll to (<a name=""> or anything with particular id)
elem = $('a[name="' + hashname + '"],#' + hashname);
if(elem) {
$(document).scrollTo(elem, 800,{onAfter:function(){
//put after scroll code here }});
}
});
See jQuery: Scroll to anchor when calling URL, replace browsers behaviour for more info.
Seems like you could use window.onscroll. I tested this code just now:
<a name="end" />
<script type="text/javascript">
window.onscroll = function (e) {
alert("scrolled");
}
</script>
which seems to work.
Edit: Hm, it doesn't work in IE8. It works in both Firefox and Chrome though.
Edit: jQuery has a .scroll() handler, but it fires before scrolling on IE and doesn't seem to work for Chrome or Firefox.
To detect when the element appears on the screen, use the appear plugin:
$('#comment-1').appear(function() {
$(this).text('scrolled');
});

Categories