javascript/jQuery location.href misses mark - javascript

I have a page that has a number of elements that are slid up on startup. I want to be able to slide down a particular pane based on the hash in the url my code is
if (window.location.hash.length>0){
var id = window.location.hash;
if (id.length==7){ //expected hash is 7 chars long (inc #)
console.log('Comment hash in url, finding link');
$(id).parents('.details_wrapper').parent().show().find('.details_wrapper').addClass('open').slideDown('slow', function(){ //unhide and slidedown pane
window.location.href = id;
});
}
}
Which sort of works in that the appropriate pane is revealed and slid down, however the window.location.href doesn't seem to be working very well as the window consistently places the page about 800px further down than where the anchor is.
As a possible side note it seems I can't verify the correct href as typing
window.location.href='#c83225';
into the developer console (Safari) gives an error. It works in the Chrome console though.

Another option to do that is
window.location.hash = 'c83225';

Related

On back or forward button press in a browser the URL changes but the content does not

The legacy website I inherited is comprised of href #links to navigate through the website. It's rather large so I don't want to recreate the whole thing, even though I know the #urls are not best practice. One enhancement that is necessary is to enable the back and forward buttons in the browser so that they will not only change the URL (which it does) but refresh the page to show the previous/forward URL's content.
If anyone could point me in a direction to make this happen, I would definitely appreciate it.
Have some javascript on your page load look for the anchor and then scrollTo it
var url = "www.website.com/#a1", idx = url.indexOf("#")
var hash = idx != -1 ? url.substring(idx+1) : "";
function scrollTo(hash) {
location.hash = "#" + hash;
}

setting window.location.href not working as expected

If the user is at url foo.com/#/veryLongToken and the response.redirectUrl is foo.com/#/veryLongToken/resultToken , in the first example, when the page is reloaded we end up at foo.com/#/veryLongToken.
In the second example, we end up at foo.com/#/veryLongToken/resultToken which is what we expect.
More info;
The URL is very long
AngularJS window-wrapper $window is used
Tested in Chrome and Safari, both displaying same behaviour
Doesn't work:
function successHandler(response) {
$window.location.href = response.redirectUrl;
/* redirectUrl might contain only changes to the hash-fragment
which is why we force a reload here */
$window.location.reload();
}
Works;
function successHandler(response) {
$window.location.hash = response.redirectUrl.substr(response.redirectUrl.indexOf('#'));
$window.location.reload();
}
I'd really like to know why the first example doesn't work. Any ideas?
UPDATE:
$window.location.href is https://foo.fo.se/#/payment/Ak1ZWDg1MDhJAwJWVElOUE5WVEZQSQMCAwIDAgMCAwIDAgMCTVlYODUwOEkDAgMCAwIDHQDSqdsSYXcT5rdNEkrClAYdawRZXF3vwZUSSb9_XHeQTFJcyJxnQXnz1V4gQCTgm7q9OYmLKMFVEaCaZM8RX6iIExvQZT7uPjtfYowjvvU-JpO8yMhTquehcBOo_JEXqCskKVStCp25qWq4GdPXgP3f1KthAO17OOAdLHKMNm8bmNW8Nj-P_xltDTV22ZHABQS_4d0DcWSDj7ZfUK3q28zZ9pLdedu3sjblzmXqDiSBNEuDQfQOjMt_s0xlayYX0qUwJwwviaZ8aB-qLRnV7KD_LvaESGrtwq7_iiNIoB1jeFAp0dSG_N1c-5V-VZ3100DbJBoecTIF4NaCS62IxfM
response.redirectUrl is
https://foo.fo.se/#/payment/AkpITDg0ODFIAwIwTDNWVkwzMzcwSgMCAwIDAgMCAwIDAgMCSkhMODQ4MUgDAgMCAwIDHTQ1Z7gveX-CH7OzdVcAtOtar9mOZQF8f4t7MFIM5b1_WU7BAEtYPfSD77sFsGmHnm4GoFMmsIHUCzscUiaP2iofV7rflegQADTieSpwbausFLn6FNmaVeZdlFEtoWr6cU1VlN09zqk4T-1cqheoDsb_jMWr3kTdZGkJh_168P99zjV324jpDIkKAZ12WFXuaphnGdNoJgP9Ka9S2aIi8LniCiJNtOq-iXL4w8JNYVyLrbOqB2QNpc__RtT5kcW9NEaPWehQx2S5CIB157RcI_WkeGJRb1DKSSuy8CFIYJVrEOlCb-GtZ9gmPhrLh6qPiumokJWSI2cUuFBDpaGAeiA/AkpITDg0ODFIAwJJTlRFUk5BTF9FUlJPUgMCAwIDAgJJTlRFUk5BTF9QUk9DRVNTX0RFQklUX05PTl9SRUNPVkVSQUJMRQMD
As a # in a URL mark an anchor, the changing of it don't trigger a page load as your bas url (foo.com/) stay the same. The window.location.href isn't ment to hadle anchor change.
If you whant to change the "anchor" part, you must use the window.location.hash for it to be detected (as in your second exemple)
Every browser has a URL length limits! the shortest one is Internet Explorer which is 2083 characters! Check it out here
And all webkit browsers Chrome, Safari, Mozilla has a limit of 100KB! You can get more details here

Javascript/Jquery window.location

I have page the has some data in tabs, Im trying to write a function so that when links are click from another page can load the page with the tabs on and show the correct tab. This is working with the code below, minus the actual changing tabs function. But for some reason using the window.location..... as a variable still scroll the page down to the matching id. Is there another way to get the string in the url after the #. Or can i do it this way but not have to jump to the id? thanks
function loadTab(){
var linkToTab = window.location.hash.substr(1);
var linkClass = '.'+linkToTab
if(window.location.hash != '') {
changeTabs(linkClass);
}else{
$('.companyLink:first').addClass('active');
$('.companyBio:first').addClass('active');
$('.companyBio:first').fadeIn();
};
}
The hash character is for anchors.
Use a question mark instead of a hash.
<a href="index.html?tabname">
and
var linkToTab = window.location.search.substr(1);
var linkClass = '.'+linkToTab
if(window.location.search != '') {
The # part of the URL is traditionally used for anchors. The 'jumping' you see is the original feature.
Modern websites and web-applications use it build a history as HTML5's history feature isn't widely supported yet.
To avoid the jumping add event.preventDefault to your links, like:
Tab1
<script type="text/javascript">
document.getElementById("tab1handle").onclick = function (event) {
event.preventDefault();
}
</script>
You can also make sure the anchor is not defined. In this case the browser will jump to the top of the page. It's up to you whether this is undesirable or not.

Named anchors in (i)frames aren't jumped to

I have html page(parent page) that contains a iframe(child page inside this iframe),
this java script function get the location where i want to scroll iframe using internal page linking.
function scrollToAnchor ()
{ //function parseParameter return the query string value from the url
var anchor = parseParameter(window.location.href,'anchor');
if (anchor != null)
{
location.hash=anchor;
}
}
but anchor value in iframe page source not in parant page,
this is not able to scroll the iframe page.how to scroll iframe page through parant page,
it works in IE and Crome but doesn't work in firefox. there is any alternative of this code.please suggest.
my parant page url is
http://localhost:8989/schoolforms/SelectForm?formTypeID=STUDENT_EMERGENCY
This is my window.location.href" value that is for iframe
http://localhost:8088/schoolforms/StudentEmergency?student=B874BCC3EA5B83670988C959E9F0036B&anchor=InsuranceInfo
after parsing anchor contains InsuranceInfo after this function url becomes like
http://localhost:8088/schoolforms/StudentEmergency?student=B874BCC3EA5B83670988C959E9F0036B&anchor=InsuranceInfo#InsuranceInfo
JQuery bbq has a nice 'deparam' function
https://github.com/cowboy/jquery-bbq/
var params = $.deparam.querystring();
window.location.hash = params['anchor']
Too many missing information to understand what exacly do you want to achieve. I guess that you need to scroll your page to the anchor with id from anchor variable of window.location.href.
I don't know how works your function parseParameter() and I need to believe that is working good.
location.hash contains the part of URL after # for example #news etc. So if you pass a string to location.hash browser will add this string to URL and scroll to the html element with the same ID.
EFFECT
http://localhost:8088/schoolforms/StudentEmergency?student=B874BCC3EA5B83670988C959E9F0036B&anchor=InsuranceInfo#InsuranceInfo
It's not a good way, because after that you will have both anchor variable and hash in your URL.
TRY THIS
function scrollToAnchor ()
{
var anchor = parseParameter(window.location.href,'anchor');
if (anchor != null)
{
$('html, body').animate({scrollTop: $('#'+anchor).offset().top}, 0);
}
}
I used .animate() because if you want you can change in this line 0 to for example default value, which is 400 (i guess ms unit) and it will scroll with animation (delay). If you leave 0 it will scroll to the element immediately without any delay.
$('html, body').animate({scrollTop: $('#'+anchor).offset().top}, 400);

Frame Busting buster not completely working for IE

I've been working on a Frame busting buster (what's in a name, hehe), which kept my users on my page and open a new window with the target URL. I'm using a Lightbox script to display iframes, this is what I'm doing:
1) Added an event for all .lightbox clicks, f.e:
$('.lightbox').live("click", function(e) {
e.preventDefault();
$('#redirectURL').val($(this).attr('href'));
$(this).lightbox();
}
2) Added a frame busting buster:
<script type="text/javascript">
var prevent_bust = 0
window.onbeforeunload = function() { prevent_bust++ }
setInterval(function() {
if (prevent_bust > 0) {
prevent_bust -= 2
window.top.location = 'http://server-which-responds-with-204.com'
}
}, 1)
</script>
3) Modified the frame busting buster code to fit my needs, which are:
detect if an iframe wants to change the window.top.location
if so, prevent this from happening using the 204 server respond
open a new page: window.open( $('#redirectURL', '_blank' );
close lightbox: $('.jquery-lightbox-button-close').click();
So far, this is what I've come up with:
var prevent_bust = 0
window.onbeforeunload = function() { prevent_bust++ }
setInterval(function() {
if (prevent_bust > 0) {
prevent_bust -= 2;
redirectURL = $('#redirectURL').val();
if(redirectURL != "") {
window.top.location = 'http://www.****.com/ajax/nocontent.php';
window.open(redirectURL, "_blank");
$('.jquery-lightbox-button-close').click();
$('#redirectURL').val('');
} else {
window.top.location = 'http://www.****.com/ajax/nocontent.php';
}
}
}, 1);
// EDIT: Before I forget, 'nocontent.php' is a file that returns a 204 header
For Firefox it acts as I programmed it, if there's a change detected in the window.top.location it opens a new frame/page and prevents the iframe from reloading the top location and to round it up, it closes the jQuery lightbox.
Safari/Chrome act similar, they open a new browser screen (not sure if theres an option to say target="_newtab" or something?). Only bad thing is they do not really display a message of the popup is blocked, but I can work around that by displaying a popup balloon on my website with a link to the page.
Internet Explorer is, what a shocker, the only black sheep left.. IE does not open a new popup, nor blocks the window.top.location reset by the iFrame and simply continues refreshing the complete page to the '#targetURL'. It does the same with the default busting code.. so it's not because of some of my edits.
Anyone who is able to spot a mistake in my code?
Also, I would need a little modification that sees if the request has been made by an iframe or by the user itself, because now there is really NO option for a user to leave my page by changing the address in the toolbar or by clicking a link, which is not really needed LOL.
Thanks in advance.
PENDO, I tried to simulate the whole process you described, ligthbox-jquery, javascript their own codes and controls opening pages via lightbox. I could not simulate at all, and as time is running out I'm sending a suggestion to broaden the range of possibilities and solutions.
I suggest replacing the redirect page:
...
redirectUrl = $ ('# redirectUrl'). val ();
...
window.top.location = 'http://www .****. with / ajax / nocontent.php';
window.open (redirectUrl, "_blank");
Replaced with a DIV container that simulates a page, using ajax calls and taking the content and overwritten the contents of the DIV.
...
$.post(redirectoURL /* or desired URL */, function(data) {
$('DIV.simulateContent').html(data);
});
...
or
...
$('DIV.simulateContent').load(redirectoURL);
...
This approach also avoids the problem of preventing the user from even leaving your page using the address bar (as you yourself mentioned).
Sorry, let me give you a complete solution, but time prevented me.
PENDO, a little more work on alternatives to the problem, I found a customizable jQuery lightbox plugin for working with custom windows yet (iframe, html, inline ajax etc.). Maybe it will help. The following link:
http://jacklmoore.com/colorbox/
If you don't need javascript running in your iframe in IE, you can set the iframe security attribute :
<iframe security="restricted" src="http://domain.com" />
http://msdn.microsoft.com/en-us/library/ms534622(v=VS.85).aspx

Categories