FadeIN FadeOUT page transition javascript bug - javascript

When I click any of my links to take me to a new HTML page, the javascript routes me to the same HTML page and not each links individual href.
Heres my code
$(document).ready(function() {
$('body').css('display', 'none');
$('body').fadeIn(1000);
$('.link').click(function(event) {
event.preventDefault();
newLocation = $('.link a').attr("href");
$('body').fadeOut(1000, newpage);
});
function newpage() {
window.location = newLocation;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="music" class="link">Music</div>
<div id="exhibition" class="link">Exhibition</div>
<div id="contact" class="link">Contact</div>
<div id="about" class="link">About</div>
My aim is to have the Page FadeIN on load and FadeOUT when a link has been clicked, I am getting my desired effect but im just not sure what this issue with the links is - Anyone know?

As #Taplar says, when you fetch the location from the link's href, you're not getting the right one. You're just fetch the first link in the document and looking at its href attribute.
You can easily fix this by replacing this (which looks for all anchor elements in the document that have an ancestor with the link class and then returns the first one it finds):
newLocation = $('.link a').attr('href');
with this (which finds all anchor elements as a child of whatever element has the click handler registered that was clicked):
newLocation = $(event.currentTarget).find('a').attr('href');
The other thing you're doing that is tricky, but doesn't necessarily break anything, is relying on newLocation being correctly shared between the click handler and the newpage function. I would suggest instead that you explicitly pass a parameter to newpage so that it is more reusable and you can be sure where the value is coming from.
You can see this working below.
$(document).ready(function() {
$('body').css('display', 'none');
$('body').fadeIn(1000);
$('.link').click(function(event) {
event.preventDefault();
newLocation = $(event.currentTarget).find('a').attr('href');
// Pass anonymous function to fadeOut that calls newpage with newLocation
$('body').fadeOut(1000, function () { newpage(newLocation); });
});
// newpage now accepts a parameter and uses it
function newpage(location) {
// Print to console so you can see what URL is getting used
// You'll always get 404 using StackOverflow's UI since they don't have the relevant pages
console.log(location);
window.location = location;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="music" class="link">Music</div>
<div id="exhibition" class="link">Exhibition</div>
<div id="contact" class="link">Contact</div>
<div id="about" class="link">About</div>

Related

jQuery Event Delegation for certain links

I'm having trouble delegating a click function to only certain links. Essentially, I'm trying to trigger a simple fadeout for all internal links that won't kill a lightbox functionality. Here's my problem (in essence):
HTML
<body>
<div id="fade">
<p>some content</p>
</div>
</body>
jQuery
$("#fade").on("click", "a", function () {
// get the href attribute
var newUrl = $(this).attr("href");
// veryfy if the new url exists or is a hash
if (!newUrl || newUrl[0] === "#") {
// set that hash
location.hash = newUrl;
return;
}
// now, fadeout the html (whole page)
$("body").fadeOut(function () {
// when the animation is complete, set the new location
location = newUrl;
});
// prevent the default browser behavior.
return false;
});
I can't figure out why this isn't working. The function isn't executed on any links. I'm trying to delegate it to all links within the wrapper id of "fade."
When I change
$("#fade").on("click", "a", function () {
to
$("document").on("click", "a", function () {
//specifying all links
The fade works perfectly, but it destroys the lightbox function that is needed for the site.
Is there a better way to delegate links for this event? Or perhaps not include the lightbox links in a different manner? Ideally I would keep the code above for executing on all links using $("document") and exclude the lightbox gallery from the function, but I don't know how I could do that.

Show toggling div based on URL

I'm trying to have an anchor link, once clicked, show a div. I have a click toggle working on the page, but in addition to that functionality, if a user clicks a sidebar link, I don't want the div to toggle, I just want it to be shown, if hidden. I've tried several if thens, etc - I think this is the closest, but still not working.
Functions (first toggles the h4, the second is my attempt to have the same div shown if a URL is loaded...or the anchor link is clicked):
<script>
$(document).ready(function(){
//Hide (Collapse) the toggle containers on load
$(".toggle_container3").hide();
//Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
$(".trigger3").click(function(){
$(this).toggleClass("active").next().slideToggle("slow");
return false; //Prevent the browser jump to the link anchor
}).first().click()
});
</script>
<script>
$(function() {
if ( document.location.href.indexOf('#papers') > -1 ) {
$("#papertoggle").show();
$("h4#papers").addClass("active");
})
});
</script>
Also tried this version, with the keyword either "papers" or "climate_change_test#papers" :
<script type="text/javascript">
// Get URL
var url = window.location.href;
// Get DIV
var msg = document.getElementById('papertoggle');
// Check if URL contains the keyword
if( url.search( 'climate_change_test#papers' ) > 0 ) {
// Display the message
msg.style.display = "block";
}
</script>
HTML of the link:
<li>Papers and Publications</li>
HTML of the h4 and div:
<h4 class="trigger3 dark_grey" id="papers">
Papers and Publications</h4>
<div class="toggle_container3" id="papertoggle"> content </div>
Entire test page:
http://www.sea.edu/sea_research/climate_change_test
This should work:
$("#over_left a").click(function(){
var id = $(this).attr("href");
$(id).toggleClass("active").next().slideToggle("slow");
});
However I would suggest to narrow down the $("#over_left a") selector so it only works on those specific submenu links.
Also tried this version, with the keyword either "papers" or "climate_change_test#papers" :
<script type="text/javascript">
// Get URL
var url = window.location.href;
// Get DIV
var msg = document.getElementById('papertoggle');
// Check if URL contains the keyword
if( url.search( 'climate_change_test#papers' ) > 0 ) {
// Display the message
msg.style.display = "block";
}
</script>
The reason why the above code didn't work, is because it is executed on page load. However, when you click an anchor tag url, the page doesn't reload (it only jumps to the relevant anchor div), so this code is never executed.
Please also be aware that you don't need a complicated search to look for the "#papers" part in your url. You can simply use:
window.location.hash
To find the anchor part at the end of your url.
So combining all of the info from above, you can also create a function that deals with the following example: What if someone shares a link with an anchor url? It should automatically expand already then, right?
// On page load
var anchor = window.location.hash;
// If there is an anchor in the URL, expand the relevant div
if (anchor) {
$(anchor).toggleClass("active").next().slideToggle("slow");
}

Adding an onMouseDown attribute equivalent to each anchor's HREF attribute in a class or document

I'm having trouble getting an onMouseDown function that takes each link and copies the original HREF attribute of its respective anchor tag in a page and loads the URL on the down event.
Let's call this function loadURL().
Right now I'm testing the function in-line for each anchor and am having trouble getting different values for each HREF attribute. I would like to make an onLoad function that essentially adds the onMouseDown attribute and loadURL function to every anchor. Here's the JQuery code I have now.
PROBLEM SOLVED, SHOWING INITIAL PROBLEM FOR REFERENCE
Script:
function loadURL()
{
var url = $('a').attr('href');
location.href = url;
}
function mouseDownerURL () {
$('a').attr('onmousedown', 'loadURL()' );
}
HTML
<body onLoad="mouseDownerURL();">
<a onmousedown="" href="foo.com">Takes you to foo.com on mouseDown</a>
<a onmousedown="" href="bar.com">Leads to foo.com NOT bar.com on mouseDown</a>
</body>
SOLUTION
function mouseDownerURL() {
$(document).ready(function() {
$('a').mousedown(function() {
window.location.href = this.href;
});
});
}
<body onLoad="mouseDownerURL();">
1
2
...
Get rid of all of those functions and onload things and just do it normally:
$(document).ready(function() {
$('a').mousedown(function() {
windows.location.href = this.href;
});
});
Your problem is this line:
var url = $('a').attr('href');
$('a') selects all of the <a> tags, not the one that was clicked. To work around that, you have to pass the element into your function via an argument, but that's not a great idea.

Window onhashchange not working

I have a web page that contains two articles. Upon loading this page, jQuery is used to hide the two articles and slide down the first one. User can click on the navigation tab to view the second article. Then go back to the first article by clicking the back button using the onhashchange event. The following is my HTML code:
<nav>
<a href='#1'>Article 1</a>
<a href='#2'>Article 2</a>
</nav>
<article id=1>
The first article.
</article>
<article id=2>
The second article.
</article>
And here is the javascript code:
function change(hash)
{
$('article:visible').slideUp();
if(hash != '')
{
$(hash).slideDown();
}
else
{
$('article').first().slideDown();
}
}
$('nav a').click(function(){
var id = $(this).attr('href');
change(id);
});
$('article').hide();
change(location.hash);
window.onhashchange = change(location.hash);
What was observed is that the page remains on the second article despite clicking the back button. I am using firefox 12.0 browser and don't know what is causing it not to work. Any help is appreciated. Thanks.
You might want to try:
window.onhashchange = change;
//and read location.hash in the change function instead
function change(){
var hash = location.hash;
...
}
or
window.onhashchange = function(){
change(location.hash);
}
window.onhashchange = change(location.hash);
If my JS ain't rusty, this fails because
calls change()
functions that have no return return undefined
you are assigning undefined to window.onhashchange - which is wrong because you're supposed to assign a function to an event.

Create a dual function html Url Link?

Problem:
You have a regular set of URL links in a HTML page e.g.:
Foo Bar
You want to create a JavaScript function such that when any HTML links are clicked, instead of the client's browser navigating to that new URL "/foo/bar" a JavaScript function is executed instead (e.g. this may for example make an Ajaxian call and load the HTML data without the need to reload the page).
However if the JavaScript is disabled OR a spider crawls the site, the UTL links are maintained gracefully.
Is this possible? Does it already exist? What's the usual approach?
EDIT 1:
These are some great answers!
Just a follow on question:
If the user clicks on the back button OR forward button, this would naturally break (as in it would go back to the last physical page it was on as opposed to one that was loaded).
Is there any way (cross browser) to maintain the back/forward buttons?
(e.g create an array of links clicked and over ride the browser buttons and use the array to navigate)?
<script type="text/javascript">
function your_function() {
alert('clicked!');
}
</script>
<a onclick="your_function();" href="/foo/bar">Foo Bar</a>
If Javascript is off, the link behaves normally.
In this case, unless your_function() does not return false, the link will be followed when clicked as well.
To prevent this, either make your_function() return false, or add return false; just after the function call in your onclick attribute:
<script type="text/javascript">
function your_function() {
alert('clicked!');
return false;
}
</script>
<a onclick="your_function();" href="/foo/bar">Foo Bar</a>
Or:
<script type="text/javascript">
function your_function() {
alert('clicked!');
}
</script>
<a onclick="your_function(); return false;" href="/foo/bar">Foo Bar</a>
Using element.addEventListener()
With default anchor behaviour following click:
<script type="text/javascript">
document.addEventListener("load", function() {
document.getElementById("your_link").addEventListener("click", function() {
alert('clicked');
}, true);
}, true);
</script>
<a id="your_link" href="/foo/bar">Foo Bar</a>
Without:
<script type="text/javascript">
document.addEventListener("load", function() {
document.getElementById("your_link").addEventListener("click", function(event) {
event.preventDefault();
alert('clicked');
}, true);
}, false);
</script>
<a id="your_link" href="/foo/bar">Foo Bar</a>
Given current HTML and W3C APIs, I would go for:
<script src="linkify.js"> </script>
in the markup, with linkify.js containing something like:
window.onload= function() {
document.addEventListener('click', function(ev) {
ev.preventDefault();
var el = ev.target;
if (el.tagName === 'A') {
// do stuff with el.href
}
}, false);
};
See e.g. http://jsfiddle.net/alnitak/nrC7G/, or http://jsfiddle.net/alnitak/6necb/ for a version which doesn't use window.onload.
Note that this code uses a single listener function registered on the document object, which will act on every <A> tag on the page that doesn't trap clicks for itself.
Use an onclick attribute:
click?
The return false prevents the default behaviour, in the absence of JavaScript, however, the link will be followed.
function do_whatever (e)
{
e.preventDefault ();
// do whatever you want with e.target
}
var links = document.getElementsByTagName ("a");
for (var i=0; i<links.length; ++i)
links[i].addEventListener ('click', do_whatever);
http://jsfiddle.net/bTuN7/
All done inside script and it won't 'hurt' if JavaScript doesn't work.
If you think about AJAX, then you have to know, that googlebot tries to parse it. http://www.youtube.com/watch?v=9qGGBYd51Ts
You can code like:
$('a').click(function() {
doSomethingWithURL($(this).attr('href'));
return false;
});
JavaScript is not executed in case it's disabled or if it's some web crawler, so from my point of view this is preferable.
There's quite a few methods out there such as this:
http://www.malbecmedia.com/blog/development/coding-a-ajax-site-that-degrades-gracefully-with-jquery/
Remember, though, that by virtue of a well setup server and caching you're not going to gain yourself much performance with an Ajax Load.

Categories