How do I change the title of a web page using javascript? - javascript

I know this is a duplicate question, but I've tried a few approaches and I'm not able to get the solution I need.
I need to change the title of a web page, and I thought Javascript would be a good candidate. I've read many disapproving comments already, talking about how changing the title will negatively affect SEO-I'm not worried about that just now.
I'm able to change the title by reassigning a value in an inline script:
<input type="button" value="Click me." onclick="document.title = 'Some new title';" />
But using an inline script in this case is out of the question. I tried loading an embedded script tag above & below the body of the script, no go. This is what I settled on, and it didn't work initially (keep reading):
<script>
document.addEventListener("load", function changeTitle(){
document.title = "FUBAR";
}, true);
</script>
I've tried adding/removing the 'true' value at the end of the parameter list and that doesn't change anything. I avoided naming the function, then named it, and that didn't change anything. What DID work was changing "load" to "click". I need the title to change right after the document is finished loading...is there something else I can use, like "ready", or "onload"? Using "load" yielded no results, but I swear I've seen it used before.
Thanks!

Try using
window.addEventListener rather than document.addEventListener
See
https://developer.mozilla.org/en-US/docs/Web/Events/load
Note: More reliable is to add event listener on
"window.addEventListener".

No need to wait for the load event. Just set the title:
<html>
<head></head>
<body>
<script>document.title = "foobar"</script>
<!-- rest of document -->

Related

How do I set specific key for keydown event listener? [duplicate]

I am trying to use an HTML button to call a JavaScript function.
Here's the code:
<input type="button" value="Capacity Chart" onclick="CapacityChart();">
It doesn't seem to work correctly though. Is there a better way to do this?
Here is the link:http://projectpath.ideapeoplesite.com/bendel/toolscalculators.html click on the capacity tab in the bottom left section. The button should generate an alert if the values are not changed and should produce a chart if you enter values.
There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations.
1: There's defining it in the HTML:
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
2: There's adding it to the DOM property for the event in Javascript:
//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;
//- Using an anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };
3: And there's attaching a function to the event handler using Javascript:
var el = document.getElementById("clickMe");
if (el.addEventListener)
el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
el.attachEvent('onclick', doFunction);
Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification.
The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too.
Most likely, the problem lies somewhere in your CapacityChart() function. After visiting your link and running your script, the CapacityChart() function runs and the two popups are opened (one is closed as per the script). Where you have the following line:
CapacityWindow.document.write(s);
Try the following instead:
CapacityWindow.document.open("text/html");
CapacityWindow.document.write(s);
CapacityWindow.document.close();
EDIT
When I saw your code I thought you were writing it specifically for IE. As others have mentioned you will need to replace references to document.all with document.getElementById. However, you will still have the task of fixing the script after this so I would recommend getting it working in at least IE first as any mistakes you make changing the code to work cross browser could cause even more confusion. Once it's working in IE it will be easier to tell if it's working in other browsers whilst you're updating the code.
I would say it would be better to add the javascript in an un-obtrusive manner...
if using jQuery you could do something like:
<script>
$(document).ready(function(){
$('#MyButton').click(function(){
CapacityChart();
});
});
</script>
<input type="button" value="Capacity Chart" id="MyButton" >
Your HTML and the way you call the function from the button look correct.
The problem appears to be in the CapacityCount function. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.
Edit:
Looks like document.all is an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById(), it should probably work. Example: document.getElementById("RUnits").value instead of document.all.Capacity.RUnits.value
This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code
Just so you know, the semicolon(;) is not supposed to be there in the button when you call the function.
So it should just look like this: onclick="CapacityChart()"
then it all should work :)
One major problem you have is that you're using browser sniffing for no good reason:
if(navigator.appName == 'Netscape')
{
vesdiameter = document.forms['Volume'].elements['VesDiameter'].value;
// more stuff snipped
}
else
{
vesdiameter = eval(document.all.Volume.VesDiameter.value);
// more stuff snipped
}
I'm on Chrome, so navigator.appName won't be Netscape. Does Chrome support document.all? Maybe, but then again maybe not. And what about other browsers?
The version of the code on the Netscape branch should work on any browser right the way back to Netscape Navigator 2 from 1996, so you should probably just stick with that... except that it won't work (or isn't guaranteed to work) because you haven't specified a name attribute on the input elements, so they won't be added to the form's elements array as named elements:
<input type="text" id="VesDiameter" value="0" size="10" onKeyUp="CalcVolume();">
Either give them a name and use the elements array, or (better) use
var vesdiameter = document.getElementById("VesDiameter").value;
which will work on all modern browsers - no branching necessary. Just to be on the safe side, replace that sniffing for a browser version greater than or equal to 4 with a check for getElementById support:
if (document.getElementById) { // NB: no brackets; we're testing for existence of the method, not executing it
// do stuff...
}
You probably want to validate your input as well; something like
var vesdiameter = parseFloat(document.getElementById("VesDiameter").value);
if (isNaN(vesdiameter)) {
alert("Diameter should be numeric");
return;
}
would help.
Your code is failing on this line:
var RUnits = Math.abs(document.all.Capacity.RUnits.value);
i tried stepping though it with firebug and it fails there. that should help you figure out the problem.
you have jquery referenced. you might as well use it in all these functions. it'll clean up your code significantly.
I have an intelligent function-call-backing button code:
<br>
<p id="demo"></p><h2>Intelligent Button:</h2><i>Note: Try pressing a key after clicking.</i><br>
<button id="button" shiftKey="getElementById('button').innerHTML=('You're pressing shift, aren't you?')" onscroll="getElementById('button').innerHTML=('Don't Leave me!')" onkeydown="getElementById('button').innerHTML=('Why are you pressing keys?')" onmouseout="getElementById('button').innerHTML=('Whatever, it is gone.. maybe')" onmouseover="getElementById('button').innerHTML=('Something Is Hovering Over Me.. again')" onclick="getElementById('button').innerHTML=('I was clicked, I think')">Ahhhh</button>

Inline Editing But Instance Doesn't Exist

I have my own custom non-jQuery ajax which I use for programming web applications. I recently ran into problems with IE9 using TinyMCE, so am trying to switch to CKeditor
The editable text is being wrapped in a div, like so:
<div id='content'>
<div id='editable' contenteditable='true'>
page of inline text filled with ajax when links throughout the site are clicked
</div>
</div>
When I try to getData on the editable content using the examples in the documentation, I get an error.
I do this:
CKEDITOR.instances.editable.getData();
And get this:
Uncaught TypeError: Cannot call method 'getData' of undefined
So I figure that it doesn't know where the editor is in the dom... I've tried working through all editors to get the editor name, but that doesn't work-- no name appears to be found.
I've tried this:
for(var i in CKEDITOR.instances) {
alert(CKEDITOR.instances[i].name);
}
The alert is just blank-- so there's no name associated with it apparently.
I should also mention, that despite my best efforts, I cannot seem to get the editable text to have a menu appear above it like it does in the Massive Inline Editing Example
Thanks for any assistance you can bring.
Jason Silver
UPDATE:
I'm showing off my lack of knowledge here, but I had never come across "contenteditable='true'" before, so thought that because I was able to type inline, therefore the editor was instantiated somehow... but now I'm wondering if the editor is even being applied to my div.
UPDATE 2:
When the page is loaded and the script is initially called, the div does not exist. The editable div is sent into the DOM using AJAX. #Zee left a comment below that made me wonder if there is some other command that should be called in order to apply the editor to that div, so I created a button in the page with the following onclick as a way to test this approach: (adapted from the ajax example)
var editor,html='';config = {};editor=CKEDITOR.appendTo('editable',config, html );
That gives the following error in Chrome:
> Uncaught TypeError: Cannot call method 'equals' of undefined
> + CKEDITOR.tools.extend.getEditor ckeditor.js:101
> b ckeditor.js:252
> CKEDITOR.appendTo ckeditor.js:257
> onclick www.pediatricjunction.com:410
Am I headed in the right direction? Is there another way to programmatically tell CKEditor to apply the editor to a div?
UPDATE 3:
Thanks to #Reinmar I had something new to try. The most obvious way for me to test to see if this was the solution was to put a button above the content editable div that called CKEDITOR.inlineAll() and inline('editable') respectively:
<input type='button' onclick=\"CKEDITOR.inlineAll();\" value='InlineAll'/>
<input type='button' onclick=\"CKEDITOR.inline('editable');\" value='Inline'/>
<input type='button' onclick=\"var editor = CKEDITOR.inline( document.getElementById( 'editable' ) );\" value='getElementById'/>
This returned the same type of error in Chrome for all three buttons, namely:
Uncaught TypeError: Cannot call method 'equals' of undefined ckeditor.js:101
+ CKEDITOR.tools.extend.getEditor ckeditor.js:101
CKEDITOR.inline ckeditor.js:249
CKEDITOR.inlineAll ckeditor.js:250
onclick
UPDATE 4:
Upon further fiddling, I've tracked down the problem being related to json2007.js, which is a script I use which works with Real Simple History (RSH.js). These scripts have the purpose of tracking ajax history, so as I move forward and back through the browser, the AJAX page views is not lost.
Here's the fiddle page: http://jsfiddle.net/jasonsilver/3CqPv/2/
When you want to initialize inline editor there are two ways:
If element which is editable (has contenteditable attribute) exists when page is loaded CKEditor will automatically initialize an instance for it. Its name will be taken from that element's id or it will be editor<number>. You can find editors initialized automatically on this sample.
If this element is created dynamically, then you need to initialize editor on your own.
E.g. after appending <div id="editor" contenteditable="true">X</div> to the document you should call:
CKEDITOR.inline( 'editor' )
or
CKEDITOR.inlineAll()
See docs and docs.
You can find editor initialized this way on this sample.
The appendTo method has different use. You can initialize themed (not inline) editor inside specified element. This method also accepts data of editor (as 3rd arg), when all other methods (CKEDITOR.inline, CKEDITOR.replace, CKEDITOR.inlineAll) take data from the element they are replacing/using.
Update
I checked that libraries you use together with CKEditor are poorly written and cause errors you mentioned. Remove json2007.js and rsh.js and CKEditor works fine.
OK, so I have tracked down the problem.
The library I was using for tracking Ajax history and remembering commands for the back button, called Real Simple History, was using a script called json2007 which was intrusive and extended native prototypes to the point where things broke.
RSH.js is kind of old, and I wasn't using it to it's full potential anyway, so my final solution was to rewrite the essential code I needed for that, namely, a listener that watched for anchor (hash) changes in the URL, then parsed those changes and resubmitted the ajax command.
var current_hash = window.location.hash;
function check_hash() {
if ( window.location.hash != current_hash ) {
current_hash = window.location.hash;
refreshAjax();
}
}
hashCheck = setInterval( "check_hash()", 50 );
'refreshAjax()' was an existing function anyway, so this is actually a more elegant solution than I was using with Real Simple History.
After stripping out the json2007.js script, everything else just worked, and CKEditor is beautiful.
Thanks so much for your help, #Reinmar... I appreciate your patience and effort.

Dynamically change page title from h1 tag using Javascript

First off, thanks for taking the time to read this question. What a great community Stack Overflow has :)
I need to change the title tag of a page based on the text contained in the h1 element on that page.
I've been searching around, and I have found the "document.title" Javascript function. I've been playing around with it, trying to pull the text from my h1 element that has the class of "Category-H1".
<script type="text/javascript">
document.title = document.getElementsByClassName("Category-H1");
</script>
However, it is just setting the page title to "[object HTMLCollection]", which as I understand is a null value. Is JS the best was to do this? I know my code is jacked, any tips?
Thanks in advance! - Alex
Edit
I have been informed that line of code returns a collection object and not a string. It was pointed to a code example of:
setTimeout(function () { document.title = "iFinity User Profile - " + document.getElementById("test").outerText; }, 1000);
However, this code produces a page title of "iFinity User Profile - undefined". I have the h1 element on that page set to the id of "test".
You're almost there.
[object HTMLCollection] is not a null value--it is the string representation of a collection of html elements. You want to choose the first one and then get the inner html from it.
document.getElementsByClassName("Category-H1")[0].innerHTML
Also, make sure you do this after the document has loaded. You can either do this by adding the script at the end of your document, or have it run on the onload event of the body.
This should work:
document.title = document.getElementsByClassName("Category-H1")[0].innerHTML;
The getElementsByClassName() function returns a collections of elements ( [object HTMLCollection], so you need to get an element out of it, I'm assuming the first one.
A better solution may be the following:
<script type="text/javascript">
document.title = document.getElementsByTagName("H1")[0].innerHTML
</script>
This would save from setting a h1 class.
This is very close, but I found that - working with Firefox anyway, when you use the getElementsByTagName("H1") it gives you an array as you have recognized. However, it works better using:
<script type="text/javascript">
document.title = document.getElementsByTagName("H1").item(0).innerHTML;
</script>
Note the addition of the .item(0).innerHTML after getting the element rather than the [0].innerHTML.
I don’t know if you have any experience in it or not, but another alternative that seems to be very popular these days is the use of jQuery. As in the earlier discussions, the code below assumes that you are interested in grabbing the first instance of the “H1” tag or the “Category-H1” class. This is an important point because unless you target an “ID” attribute, you will get a collection of items.
This code also assumes that you have already implemented the inclusion of the jQuery library either directly from your website or by referencing a CDN.
<script type="text/javascript">
$(document).ready(function () {
document.title = $("H1")[0].innerText;
});
</script>
The $(document).ready will call it’s enclosed function only after the Document Object Model (DOM) has finished loading, and before the browser’s rendering engine displays the page.
The content inside the function will grab the inner text of the first instance of the “H1” tag and assign that text value to the document’s title tag in the head section.
I hope this adds another layer of help.

Replacing HTML with Javascript in a way that is executable in a browser

I have no Javascript experience at all. What I want is to replace a single instance of a block of text in a page's HTML - how can I do this?
30 minutes of reading around has brought me this:
javascript:document.body.innerHTML = document.body.innerHTML.replace("this","that");
Am I even close?
With no experiance at all I recommend you take a look at jQuery. With jQuery you can do:
Given:
<p>block of text</p>
jQuery:
$('p').text("some other block of text");
javascript:document.body.innerHTML = "that"
1) If it is part of a URL, such as <a href="...">, then you need
javascript:void(document.body.innerHTML = document.body.innerHTML.replace("this","that"));
2) If it is part of an event, such as <button onClick="...">, then you need
document.body.innerHTML = document.body.innerHTML.replace("this","that");
3) If you are trying to replace ALL instances of "this" with "that", and not just the first, then you need
... .replace(/this/g,"that")
You cannot just execute that script in the address bar. It needs to operate on a document, but there is nothing to replace there. Executing javascript from the address bar will give you a new empty document on which that code operates.
Even if you try to load a document from javascript, the rest of your script gets executed first. Try this:
javascript:window.location='http://www.google.com';alert(document.innerHTML);
You'll see that the alert pops up before the page is loaded, and it shows 'undefined'.
Even when you try binding to the onload event of the document or the window it won't work. Probably because they are reset afterwards.
javascript:window.location='http://www.google.com';window.onload=function(){alert(document.innerHTML);};
And it makes sense; if this would work, you could manipulate the next page when jumping to that page, thus making it possible to inject javascript in a page you link to. That would be a big security issue, so it's a good thing this doesn't work.

Javascript error: [elementname] has no properties

I'm doing some maintenance coding on a webapp and I am getting a javascript error of the form: "[elementname] has no properties"
Part of the code is being generated on the fly with an AJAX call that changes innerHTML for part of the page, after this is finished I need to copy a piece of data from a hidden input field to a visible input field.
So we have the destination field: <input id="dest" name="dest" value="0">
And the source field: <input id="source" name="source" value="1">
Now when the ajax runs it overwrites the innerHTML of the div that source is in, so the source field now reads: <input id="source" name="source" value="2">
Ok after the javascript line that copies the ajax data to innerHTML the next line is:
document.getElementById('dest').value = document.getElementById('source').value;
I get the following error: Error: document.getElementById("source") has no properties
(I also tried document.formname.source and document.formname.dest and same problem)
What am I missing?
Note1: The page is fully loaded and the element exists. The ajax call only happens after a user action and replaces the html section that the element is in.
Note2: As for not using innerHTML, this is how the codebase was given to me, and in order to remove it I would need to rewrite all the ajax calls, which is not in the scope of the current maintenance cycle.
Note3: the innerHTML is updated with the new data, a whole table with data and formatting is being copied, I am trying to add a boolean to the end of this big chunk, instead of creating a whole new ajax call for one boolean. It looks like that is what I will have to do... as my hack on the end then copy method is not working.
Extra pair of eyes FTW.
Yeah I had a couple guys take a look here at work and they found my simple typing mistake... I swear I had those right to begin with, but hey we live and learn...
Thanks for the help guys.
"[elementname] has no properties" is javascript error speak for "the element you tried to reference doesn't exist or is nil"
This means you've got one or more of a few possible problems:
Your page hasn't rendered yet and you're trying to reference it before it exists
You've got a spelling error
You've named your id the same as a reserved word (submit on a submit button for instance)
What you think you're referencing you're really not (a passed variable that isn't what you think you're passing)
Make sure your code runs AFTER the page fully loads. If your code runs before the element you are looking for is rendered, this type of error will occur.
What your describing is this functionality:
<div id="test2">
<input id="source" value="0" />
</div>
<input id="dest" value="1" />
<script type="text/javascript" charset="utf-8">
//<![CDATA[
function pageLoad()
{
var container = document.getElementById('test2');
container.innerHTML = "<input id='source' value='2' />";
var source = document.getElementById('source');
var dest = document.getElementById('dest');
dest.value = source.value;
}
//]]>
</script>
This works in common browsers (I checked in IE, Firefox and Safari); are you using some other browser or are you sure that it created the elements correct on innerHTML action?
It sounds like the DOM isn't being updated with the new elements to me.
For that matter, why are you rewriting the entire div just to change the source input? Wouldn't it be just as easy to change source's value directly?
This is a stretch, but just may be the trick - I have seen this before and this hack actually worked.
So, you said:
Ok after the javascript line that copies the ajax data to innerHTML the next line is:
document.getElementById('dest').value = document.getElementById('source').value;
Change that line to this:
setTimeout(function() {
document.getElementById("dest").value = document.getElementById("source").value;
}, 10);
You really shouldn't need this, but it is possible that the time between your setting the innerHTML and then trying to access the "source" element is so fast that the browser is unable to find it. I know, sounds completely whack, but I have seen browsers do this in certain instances for some reason that is beyond me.
Generally you shouldn't use innerHTML, but create elements using DOM-methods. I cannot say if this is your problem.

Categories

Resources