Use variable thats filled in later javascript - javascript

In the header
I have a link
Header
document.write('<a href="example.com/index.html?week=' + WeekW + '">');
The body changes based on the content so the WeekW changes with it.
Body
var WeekW = 53;
Ofcourse it gives me now it does not exist...what can be done ?

You have a few choices:
Set your variable before the document.write. This seems unlikely, since from what you say, you don't know the value of WeekW when you're writing your line.
Write a placeholder, and once you calculate your WeekW, you can fill in the placeholder. The easiest way to do this is simply write an anchor with a unique id:
document.write('<a id="myUniqueIdRightHere" >');
Later on, when you have set WeekW, go back and change your anchor:
document.getElementById('myUniqueIdRightHere').href = "example.com/index.html?week=" + WeekW;
Another alternative is to insert the full anchor with complete href into the document in the appropriate position after WeekW is set. You'd need to know enough about the surrounding parts of the document, but should be able to find something and attach the anchor at that point using things like the get* functions and appendChild.

Related

jQuery, append only part of an element without losing its content (possibly with clone?)

I'll start by saying I'm not overly confident with my web development abilities and its entirely possible I'm going about this all wrong, but anyway here goes.
I would like to be able to .append on a small part of an element (target of where to open the link) as I don't know what its content will be.
For the purposes of demonstration, I use this below to append all the results I get back from a search request.
$("#results").append("<div><a href='http://en.wikipedia.org/wiki/" + encodeURIComponent(item.title) + "'>" + item.title + "</a> : " + item.snippet + "</div>");
What I would like to be able to do is to further append these results when the user clicks on one of the links, the Target for this would be a new tab within the webpage which isn't present at the time of the first .append (also achieved with jQuery)
I was thinking I could try to use .clone to get the content of the div, remove the html (as to end up with just the link) and then use this as input into another .append
Am I going about this in the wrong way? I worry that attempting to change the HTML for the link when the user clicks on it will cause problems.
Any advice would be greatly appreciated!
Thanks for your time
I'm not sure that you need to clone the div element. You might be able to achieve what you want by attaching a click handler for the link:
$('#results').append('div>[ your code from above ]</div>')
.find('a')
.bind('click', function(e) {
e.preventDefault();
var a = $(this);
var url = a.attr('href'); // here is the url
// call some other function
});
My apologies if I have missed what you are trying to do here. But hope this helps you.

Changing page using window.location

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

Get css width from a string

I have a string that I want to display on a web page that is dynamically passed in. I want to be able to dynamically determine the css width needed to display this string and then wrap it in an html element with the exact size needed to display it.
I am currently using javascript and dojo, so answers using those two are fine, but anything else won't work.
More Detail
I guess I should clarify. I want to display the string in an input field, so not as simple as a div (I think at least)
If you're wanting to set the <input> length to show all characters in the string, you can set it like so:
var myString = "abcdefg"; // this is what got input dynamically
var myInputElement = document.getElementById('someInput');
myInputElement.size = myString.length;
Since usually a good measure of characters are by em.
You can do this;
var element = Document.getElementById("ID");
element.style.length = element.value.length + " em";
You have to remember that before calculating the string's pixel width with regards to it's character count you have to somehow be aware of the metrics on the font used.
If then, you were to take the input string, wrap it in a <span>, embed it in the document, calculate the element's width, then remove the span and add the value to it's final destination you'd have a pretty decent projection of the intended width as long as your span has the same font style rules as the destination element.
If you want to get really fancy and technical about it, then the HTML 5 <canvas> tag is your friend.
A good article to better understand the complexity of font metrics in javascript which will also help you solve this: http://mudcu.be/journal/2011/01/html5-typographic-metrics/#measure
you can create an element and put some callback in it's load event
var span = $("<span/>").text("your input").load(function(e){
console.log($(this).width());
});
this way you can get the current width. don't define any width for the span element and don't float.

Measuring the string width in Javascript

I'm trying to precisely fit a string into a certain width. This means the font-size changes depending on the string. I now use the following function, using jQuery:
function fontResize ( )
{
for (var i = $("#date").css("font-size").slice(0, -2); $("#date").width() < $("#clock").width(); i++)
$("#date").css("font-size", i.toString() + "px");
}
The idea is that I set the font-size in the CSS to the lowest possible value. I initialize the loop with this value and increment the font-size with 1 until the string is wider than the width of the containing element. The string in this case is "date" and the containing element is "clock".
Although this works, I think the main disadvantage is that the string has to be first drawn before the width can be determined. This means I cannot call this function before loading the body.
If anyone knows a better way to do this please let me know! Thanks.
To make sure you're getting all the styles and such applied to it that will be applied when the page is fully rendered, yes, you do want to put the element in the DOM (and in the right place in the DOM) before you do your measurement stuff. But you don't have to wait until everything else is there (unless you think it will affect the styling of the string you're measuring). You can put your code in a script block immediately after the element in question — no waiting for ready. The date element will be there and accessible, according to Google's Closure library engineers. E.g., if date is a span:
<body>
...
<span id="date">December 13th</span>
<script>fontResize();</script>
...
...
</body>
It's unfortunate to intermix code and markup like that (particularly if you have separate teams doing the markup and the code), but if your requirement is to size the text absolutely as soon as possible, that's how.
The above also assumes your fontResize function is already loaded (e.g., in a script block higher on the page). This is another reason it's unfortunate to mix markup and code like this, because normally of course you want to put your scripts at the bottom, just before closing the body tag.
However: It may be worth experimenting to see if you can do your resizing in the script you put just before the closing body tag instead. There'd be a small window of opportunity for the page not to look right, but quite small and of course pages tend to look a little funny as they load anyway. Then you wouldn't have the intermixing problem and wouldn't have to load your scripts early. You may find that the just-before-the-closing-body-tag is soon enough.
How about using the canvas, and the measureText method?
$(function () {
var canvas = $("canvas")[0];
var context = canvas.getContext("2d");
var text = "hello world";
context.font = "40pt Calibri";
var metrics = context.measureText(text);
alert(metrics.width);
});

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