Javascript dynamic link issues? - javascript

There might be a duplicate of this (I've tried checking questions on creating dynamic links but they reference a static link - I want this link to be hidden from the user). On testing the following code on the ww3 site:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
document.write("<a href="www.google.com">Google</a>");
</script>
</body>
</html>
I get:
http://www.w3schools.com/jsref/%22www.google.com%22
As the link address rather than www.google.com.
How do I correct this problem? And how do I make it so the link only appears after a set time? Note, this is a simplified version of the code for readability (the dynamic link will including two floating point variables assigned at the time the script is run).

An <a> tag's href must include the protocol http://, otherwise it links to a document relative to the page the link is on:
// Print quote literals, not html entities `"`
document.write("<a href='http://www.google.com'>Google</a>");
The use cases for document.write() are often limited since it can't be used after the page has loaded without overwriting the whole thing. A lot of the time you will want to create the element after the page has already rendered. In that case, you would use document.createElement() and appendChild().
// Create the node...
var newlink = document.createElement('a');
newlink.href = 'http://www.google.com';
// Set the link's text:
newlink.innerText = "Google";
// And add it to the appropriate place in the DOM
// This just sticks it onto the <body>
// You might, for example, instead select a specific <span> or <div>
// by its id with document.getElementById()
document.body.appendChild(newlink);
By the way, w3schools is not affiliated with the W3C, and their examples are generally not recommended since they are often out of date or incomplete.

You have 2 issues:
1) You need http:// before the URL so it's: http://www.google.com
2) You don't need to use quotes in document.write, but if you want to you can do one of these 3:
document.write('Google');
document.write("<a href='http://www.google.com'>Google</a>");
document.write("<a href=http://www.google.com>Google</a>");

Use the slash "\" to escape the quote

To make the link absolute, include the "http://" at the start of the url. Write out:
<a href="http://www.google.com">
instead of
<a href="www.google.com">
The second example will be treated as a relative url, like index.html for example.

Related

How to prevent canonical URL's

I have an anchor link on home.php which goes link this:
<a href='#?id=$thought_id' class='toggle-comment' data-id='$thought_id' '> Comments ($num_of_comments) </a>
When hovering over this anchor link, I expect to see results like this:
localhost/#?id=210
But what I am getting it this:
localhost/home.php#?id=211
I have seen a similar question here: But, having applied what the best answer suggests, I still get the same results. I also have the exact same anchor link present on profile_page.php and it works perfectly there.
The anchor link is not meant to go anywhere, on click, it dynamically enlarges the div below it, showing comments.
Edit:
How anchor link works:
when clicked, the anchor link expands the div below it. When clicked, this div appears: echo "<div id='toggleComment$thought_id' class='new_comment'>";
Then for each new comment added to this thought, another div is echo'd
<div class='new_comm' id='thoughtId".$thought_id."-childId".$comment['id']."'>
JavaScript to achieve this:
$(function() {
$("a.toggle-comment").on("click", function(event) {
// prevents browser to go to href's #
event.preventDefault();
// uses Jquery's data() function to get comment id from link's data-id attribute
var id = $(this).data('id');
// get element by id and toggle display
var ele = document.getElementById("toggleComment" + id);
$(ele).toggle();
});
});
Edit 2:
Came to a conclusion with Rocki in chat. The issue was that I have the JavaScript defined twice, once in the source code of home.php and once in functions.js which was also in the head of home.php. Removed the script from the source code, and code began to function.
Everything behind # is interpreted as the hash fragment and not send to the server. Instead your browser change the hash fragment for the current page.
RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax
The character "#" is excluded because it is used to delimit a URI
from a fragment identifier in URI references (Section 4).
https://www.rfc-editor.org/rfc/rfc2396
use
<a href='/#?id=$thought_id' class='toggle-comment' data-id='$thought_id' '> Comments ($num_of_comments) </a>
instead (added / before your url)

trying to understand some js codes from website

<script>
var _b = document.getElementsByTagName('base')[0], _bH = "http://mysite.org/";
if (_b && _b.href != _bH) _b.href = _bH;
</script>
Question:
Above code is the html output from one site, what does this mean? googled online, but did not find answer.
The <base href=...> element is used to specify the base URL against which all relative URLs (modulo #imported CSS) are resolved. So normally in <a href="foo.html"> the "foo.html" is interpreted as a file in the same directory as the current page, but a <base href="http://othersite.com/otherpath/bar"> tag could cause it to behave equivalently to <a href="http://othersite.com/otherpath/foo.html">
This script sets that base URL if there is a <base> tag, but has no effect otherwise.
This might be part of a misguided attempt to cause relative links to go to the http version of the site even when the containing page is served via https.
It finds the first <base> element on the page and sets its href property to "http://mysite.org/".

How to use JavaScript variable in an HTML link

The website that I am working on has a <base> tag point to a different URL than the one that the website has. What I would like to do is get around the <base> tag by using the trueURL bellow to find the url of the webpage, because i need it to construct some internal anchors, because i need the actual url of the website so the internal anchors work correctly.
The issue that im having is that i don't know how i should use the url that i store in my trueURL variable. Is it possible to use it and then add extra extensions to the url to get it to point to my anchors? Below is a rough example of what I would like to be able to do
var trueURL = window.location.href;
<html>
<ol>
<li>
Link1
</li>
<li>
Link2
</li>
<li>
Link2
</li>
</ol>
</html>
Therefore in the end i would like to have a link that looks like trueURL#link3.
Thanks in advance,
:D :D
I am working on the assumption that your real case is more complex than your example. If it isn't, then review the other answers, which may be more appropriate for what you need to do.
What this will do is...
Run on the window load event a function that will...
Find every element in the DOM that is an A tag, and...
Loop through those found A tags and check if the element has an enhance class, and if so...
Split the href at the # to get the current a element's hash value, which we will...
Combine it with the following:
'//' + location.host + location.pathname;
Giving us the current page's URL without a hash or query string. If you want the query string (what's after the ? in a URL), add location.search:
'//' + location.host + location.pathname + location.search;
Note, the // part is protocol relative, so it will use whatever the base href's protocol is, e.g., http or https. You may want to specify that, however.
Markup
Note the class attribute, which we will use to identify which a tags to manipulate.
<ol>
<li>
Link 1 -
No enhance class, should be subject to <strong>BASE HREF</strong>:
<strong class="p">» http://example.com#link1</strong>
</li>
<li>
Link 2 -
Has enhance class, should be:
<strong class="p">» http://fiddle.jshell.net/_display/#link2</strong>
</li>
<li>
Link 3 -
Has enhance class, should be:
<strong class="p">» http://fiddle.jshell.net/_display/#link3</strong>
</li>
<li>
Link 4 -
Has enhance class, should be:
<strong class="p">» http://fiddle.jshell.net/_display/#link4</strong>
</li>
</ol>​
Javascript
//--
// window.onload is not preferred, window.addEventListener
// should be used. Except that only IE9 supports it, and
// IE8 and lower do not support it, and uses window.attachEvent
// instead, which you can test for.
//
// I'm using window.onload here simply as a shortcut method and
// for clarity. This can also go in a script tag at the bottom
// of the body tag, in which case you can remove window.onload
// and use a self-calling anonymous function like:
//
// (function updateLinks(){... all the same as below ...})();
//
// This will ensure you are out of the global variable scope.
//--
window.onload = function updateLinks() {
//--
// Modern browsers can use document.getElementsByClassName
// or you can use a shiv script to add it to browsers that
// don't. I'll do it the "manual" way here, and this works
// cross-browser. The downside is that it will interate
// through every A tag on the page, looking for the "small"
// few that have the el.className we're looking for here.
//--
var els = document.getElementsByTagName("a"),
l = els.length,
trueURL = '//' + location.host + pathname,
i, el, hash;
for (i = 0; i < l; i++) {
el = els[i];
if (el.className.indexOf("enhance") != -1) {
hash = el.href.split('#');
el.href = trueURL + "#" + hash[1];
}
}
};
http://jsfiddle.net/userdude/unnH8/
Mouseover the links to see the current setting. As always, thoroughly test with real markup in multiple browsers.
If you are serious about trueURL = window.location.href then you are working WAY too hard.
Just make the link #link1 - it automatically will be relative to the current href.
If that was just an example, you may be interested in the:
<BASE href="...">
tag. This will let you change the relative href for all links in the page at once.
And you can do it with javascript by getting each <A...> DOM element and modifying the href property.
First, if you're not using base yet or are but can switch away from using it, please read:
Is it recommended to use the <base> html tag?
Which will give you many good reasons to think twice. Moral of the story: It's usually a bad idea to use base. There are good reasons, and it is useful; I have used it to great delight many times when working with designers to have local copies of the markup that I can work with but still maintain connections back into the site's assets. But for production sites, it's too clever by half.
Also, this answer was originally written for a different question that was an exact duplicate, so I'm posting this here, although there's an answer that's very similar to it already.
Do you have control over the markup or can you use a selector to get only the elements you want to effect? You could:
HTML (Note the class truelink.)
<ol>
<li>
True Link1
</li>
<li>
True Link2
</li>
<li>
True Link3
</li>
</ol>
Javascript
​window.addEventListener('load', function links(){
var base = document.getElementsByTagName('base')[0],
links = document.getElementsByClassName('truelink'),
l = links.length,
uri = 'http://www.host.tld/path?query=test';
console.log('Base:', base, ', True Links:', links);
console.log('Modifying links in five seconds...');
setTimeout(function go(){
console.log('Modifying links now...');
while (l--){
links[l].href = links[l].href.replace(base.href, uri);
}
console.log('Base: ', base, 'True Links: ', links);
}, 5000);
});​
http://jsfiddle.net/M5Hdk/
Keep in mind that this technique demonstrates using document.getElementsByClassName, which is not supported by IE until version 9. If you have to support lower versions than IE9, see Jeremy J Starcher's answer for a less "efficient" but better supported method. There's also document.querySelectorAll, which is supported by IE8 and above and all other major browsers. If you only need to support IE8, I would suggest using this to select your links over the method Jeremy demonstrates.
I also delay the change for five seconds so you can see it work. Obviously, this won't be necessary for you (most likely).
The only thing I'm not sure about right now is whether or not my .replace() will always find the base.href to replace in all browsers, so it may be better to detect the presence of a relative url before doing a replace, so you can do whatever else appropriately. For some related background on this possible "issue", see my question that deals with how browsers handle href attributes differently in the DOM:
Method for selecting elements in Sizzle using fully-qualified URLs
Also, this will perhaps work most seamlessly if it falls in an inline script tag right after the content, or at the end of body tag, in which case you will want to remove the window.addEventListener part and replace with a self-executing function.
Their are other options, all are probably a little more problematic:
Blow away the base tag altogether. If you do this, though, you'll first want to check if you need to manually insert the base.href content into the links, otherwise I'm sure things can break or become brittle.
Add an event listener to the a links you want to use your true link and manipulate it that way onclick, just don't forget to return false at the end of the click handler function, so the browser doesn't follow the link. This is probably the most seamless method, but is probably not best for all situations.
Probably others.
Be sure to test with real world markup. base is a mildly quirky tool, so manhandling it may lead to unusual side effects. You were warned.
I would have done it this way
HTML
<ol>
<li>
<a class="build">Link1</a>
</li>
<li>
<a class="build">Link2</a>
</li>
<li>
<a class="build">Link2</a>
</li>
</ol>​
Javascript/Jquery
$(function(){
var trueURL = window.location.href;
var i = 1;
$('a.build').each(function(){
$(this).attr('href', trueURL + '#link' + i);
i = i+1;
});
});
Example of working code Here

Prefixing a URL in an window.open function jQuery

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'));
});

Where can I find documentation to support this behavior?

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.

Categories

Resources