I'm looking over some previous developers code and I come across this line:
location.href = '#' + variable;
Which has the effect of updating location.hash. Remove the '#' and of course it redirects to the non-existent url. Playing around a bit it seems I can set the hash via location.href as long as the value starts with '#'. This line or similar is used a lot, but I can't seem to find any documentation the supports this behavior of it updating location.hash by setting location.href this way.
I would like to see something showing this isn't just a happy accident that this works so I don't have to re-code all the situations where this is used. Anything you can link me to would help.
Would it be better to just changes these to properly set the location.hash anyway?
Thnks
At a guess this is because setting location.href to value is supposed to have the same behaviour as clicking a link whose href=value would; it's not supposed to replace the contents of the address bar, because then you'd have to build absolute URLs everytime you wanted to use location.href.
Assigning values to location and location.href was apparently there back in Javascript 1.0, so it's entirely possible this wasn't properly specified anywhere – neither the Mozilla or Microsoft documentation go into detail. HTML5 specifies the behaviour, most likely retroactively.
This is a good place to start your journey on the location properties.
https://developer.mozilla.org/en/window.location
By the way, #something is a valid url and assigning a new url to window.location cause the browser to navigate to the new destination.
#something is called hash and direct the browser to an anchor on the current document, or to the top of the document if the anchor does not exists.
http://docstore.mik.ua/orelly/webprog/DHTML_javascript/0596004672_jvdhtmlckbk-chp-10-sect-2.html
So what happens is when you set location.href to something that is not seen as an absolute path. The browser will automatically put the current url prepended to whatever value you are trying to set it to.
So "#section1" = "www.mysitethatistoocoolforschool.com#section1"
and "section1" = "www.mysitethatistoocoolforschool.comsection1" (this does not exist)
This URLs with a '#' char are called anchor based URLs, they're not supposed to redirect the user from the page, instead they just update the position of the page by some offset, the same way as setting the location.hash you cited.
As stated by Sii this works because when you change the location.href value it's like you're clicking on a link for example then you have the following equivalence:
<a href="#toc" >Go to Table of Contents</a>
Is the same as:
location.href = "#toc";
Both of them would result in your location.hash variable to have the value toc.
Related
I've once used jQuery UI in order to add the tab feature to one of my project.
Everything was working just fine, and I noticed each tab was bound to a URL hash tag (I do not know you say it in english). As an example, once I clicked on the first tab, #Tab0 was added to my URL.
I want to reproduce this behavior in my current project. But I'm not using jQuery UI tabs, I am porting a desktop application and there are JavaScript buttons which write and replace content inside my page (in the manner of different pages, but without reloading).
How do I proceed to mimic this behavior ? Do I have to manually fetch the tag in the URL and do things accordingly all by JavaScript ?
Thanks,
u could do it this way:
creating an url with hash from current url:
var url = window.location.href + '#Tab0';
reading a hash from current url:
var hash;
if (window.location.href.indexOf('#') > -1)
{
hash = url.split('#')[1];
}
you can do this by using location.hash:
//you can set hash
location.hash = "something";
//and read it eg. http://domain.com#something
console.log(location.hash); //will return the current hash value 'something'
Also you have to remember that if your anchor tag has hashed href attribute e.g. <a href="#something"> it will be appended automatically to current url and browser will try to find given id on the page. Of course you can prevent that default behaviour.
I don't really know what to title this. I am using jQuery so that when a user clicks a div, it transfers them to a page based off the div's class:
window.location = $(this).attr('class');
Say I'm connecting from the webserver (localhost). The first click may bring me to
localhost/info
If I click on about, it will bring me to
localhost/info/about
I was wondering how to get it to transfer me to
localhost/about
instead of
localhost/info/about
Firstly, location is an object. While assigning to it does work, it's better to assign to location.href.
Also, class is a bad choice of attribute to use for this, since it's very limiting. Instead, you should consider a data attribute:
<div data-href="/about"></div>
Note the / in the attribute value. That's what you need to make requests relative to the domain. Now you get there:
location.href = this.getAttribute("data-href");
PS. Every time someone writes $(this).attr(...), a unicorn dies.
You need to use an absolute path instead of a relative one. To do that you can prepend a / to the class.
window.location = "/" + $(this).attr('class');
I have this HTML:
Track Your Package »
Somebody on this site was able to provide me with a script to prefix the URL with the domain http://www.example.com/ Here's the script:
$(document).ready(function(){
$('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick', $('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick').replace("window.open('", "window.open('http://www.example.com/"));
});
However, I am having a little trouble with this:
The first issue is where there is multiple instances of the element. Here's a fiddle: http://jsfiddle.net/VMmZx/
Instead of one anchor being signed with ID=4 and the other with ID=5 as intended, they're both being signed with ID=4.
The idea is, each window.open function should be prefixed with http://www.example.com however, the remainder of the URL should remain intact...
The second problem I'm encountering is when the element does not exist on a page, the remainder of the jQuery fails...
Here's another fiddle: http://jsfiddle.net/VPf32/
The <a> should get the class foo, but since the element does not exist on the page, the jQuery does not execute.
Since the JavaScript is being included in the HTML template of the ASP.NET server, this can create many problems.
I hope I've been clear and you can help me. Thanks.
You can use .each() to iterate over each matching element and change them individually:
$('a[onclick^="window.open(\'TrackPackage.asp"]').each(function(index, element) {
element = $(element);
element.attr('onclick', element.attr('onclick').replace(/open\('/, 'open(\'http://www.example.com/'));
});
However, I don't think using links with a href of # and an onclick opening a window is as semantic as it could be. If possible, try changing the markup to this:
Track Your Package »
Now if someone is curious where it will lead them, the browser can show something useful in the status bar when you hover over it.
If you need to adjust the behavior further, add a class and bind for the click event. When they click, prevent the default action and open the window yourself, as you did before.
Why are you doing the click even inline like that? I would just output the links like:
Link Text
And then:
$('a[target=_blank]').click(function(){
var prefix = 'http://domain.com';
window.open(prefix + $(this).attr('href'));
});
When I hover over a url in Chrome, the url is displayed in the Chrome status bar. In my case this results in an ugly javascript:bla-bla-bla reference. Is there any way to change the contents of the status bar when you hover over a link?
Thanks
Although you selected your answer, this idea is an alternative.
You can change the href attribute on mouseover to affect what the status bar says, and change it back on mouseout or click:
function showNiceLink(el, e) {
e = e || event;
el.originalHref = el.originalHref || el.href;
console.log(e.type);
if (/click|out/i.test(e.type)){
el.href = el.originalHref;
} else {
el.href = "http://Linking...";
}
}
<a href="#this is a really UGLY link #1##$$%!!&"
onmouseover="showNiceLink(this,event)"
onmouseout="showNiceLink(this,event)"
onclick="showNiceLink(this,event)">a link with an ugly <code>href</code></a>
I'm pretty sure for security reasons this isn't possible in any browser. Otherwise links to phishing sites will become much, much harder to detect, because attackers can then just place a genuine URL in the status bar while the dangerous link actually leads elsewhere...
Use an onclick event handler for your hyperlink instead, and put a real, meaningful URL in the href attribute in place of the javascript: link (even if the link is meant to be used only with JavaScript).
Your "link"
I guess you mean you want to change what destination is shown for link that is selected? In that case you most likely should put nice url in href attribute, and use onclick attribute for your javascript. Not sure that you can duplicate everything what is done by putting javascritp in href.
Assuming this is what you have:
<a onClick="blabla">Link</a>
Add href="#" to it. Then the # should be shown in stead of the javascript:blabla.
So that would be like this:
Link
It is definitely possible to achieve the desired effect. Just look at what Google puts in the status bar of its search results.
However, you need to use some kind of a trick, e.g. onclick like BoltClock suggested.
Google shows you what you would like to see - a plain, clean URL.
Underneath, however, they use a long redirect URL with monitoring parameters to track you down as you click any result link. That way Google monitors which of the search results are clicked on and which are not.
Unfortunately, most people do not realize that. Quite frankly, I would be very glad to see a browser extension which takes all this dirty tricks down and replaces "tracking" URLs with the "real ones".
I'm looking for a simple bookmarklet to take the current URL of my website and refresh it with a couple of changes. For example:
Take the current page: http://www.example.com/pages/
and change it to: https://admin.example.com/pages/
then load that new URL.
I tried searching for a bookmarklet that can do this but I couldn't find one. Can anyone point me in the right direction? Even a bookmarklet that does something like this that I can edit to suit my needs.
Just change window.location, e.g.
window.location=window.location.toString().replace(/^http:\/\/www\./,'https://admin.')
The full bookmarklet would then be:
javascript:(function() {window.location=window.location.toString().replace(/^http:\/\/www\./,'https://admin.');})()
For example you could replace a part of the string using the replace method with a regular expression.
javascript:location = location.href.replace(/http:/g, "https:" )
The above will assign the new string value to the location and trigger the page reload.
This one will change the site name
javascript:(function() {document.title=prompt("Enter Page Title");})();