I am trying to stick a news scroller on the home page of our website.
I am a bit confused by the error message I am getting because I get it on one PC but not on another:
Object Required
I am using the below code but the following line keeps throwing Object Required error when I use this file as a web user control on my default.aspx page:
el2.style.height='<%=box_height %>';
As a result, the news is not scrolling.
Any help greatly appreciated.
<uc1:NewsScroller ID="NewsScroller1" runat="server" />
<script language="VB" runat="server">
Public box_TextColor As String = "black"
Public box_height As Integer = 150
Public box_width As Integer = 166
Public box_padding As String = "0 0 0 20"
</script>
<script type="text/javascript" for="window" event="onload">
// <!CDATA[
return window_onload()
// ]]>
</script>
<script type="text/javascript">
// <!CDATA[
// <!--
var speed = 2;
function init(){
var el = document.getElementById("newsdiv");
el.style.overflow = 'hidden';
el.style.height='<%=box_height %>';
el.style.width='<%=box_width %>';
el.style.padding='<%=box_padding %>';
el.style.color='<%=box_TextColor %>';
var el2 = document.getElementById("newsdiv-p1");
el2.style.height='<%=box_height %>';
var el3 = document.getElementById("newsdiv-p2");
el3.style.height='<%=box_height %>';
//alert(document.getElementById("newsdiv-p2").style.height+document.getElementById("newsdiv-p2").style.height);
scrollFromBottom();
}
var go = 0;
var timeout = '';
function scrollFromBottom(){
clearTimeout(timeout);
var el = document.getElementById("newsdiv");
if(el.scrollTop >= el.scrollHeight-'<%=box_height %>'){
el.scrollTop = 0;
};
el.scrollTop = el.scrollTop + speed;
if(go == 0){
timeout = setTimeout("scrollFromBottom()",50);
};
}
function stop(){
go = 1;
}
function startit(){
go = 0;
scrollFromBottom();
}
// -->
function window_onload() {
init();
}
// ]]>
</script>
<%--<asp:Panel ID="newsdiv" runat="server" onmouseout="startit();" onmouseover="stop();">--%>
<div id="newsdiv" onmouseout="startit();" onmouseover="stop();" >
<p id="newsdiv-p1" class="spacer"></p>
<asp:Label ID="lblNews" runat="server" Text="News..."></asp:Label>
<p id="newsdiv-p2" class="spacer"></p>
</div>
<%--</asp:Panel>--%>
#Marcel, I suppose you mean the source (right-click, view source and copy the code)?
If so, here it is and again, thanks
<script type="text/javascript" for="window" event="onload">
// <!CDATA[
return window_onload()
// ]]>
</script>
<script type="text/javascript">
// <!CDATA[
// <!--
var speed = 2;
$(document).ready(function init(){
var el = document.getElementById("newsdiv");
el.style.overflow = 'hidden';
el.style.height='150';
el.style.width='166';
el.style.padding='0 0 0 20';
el.style.color='black';
var el2 = document.getElementById("newsdiv-p1");
el2.style.height='150';
var el3 = document.getElementById("newsdiv-p2");
el3.style.height='150';
//alert(document.getElementById("newsdiv-p2").style.height+document.getElementById("newsdiv-p2").style.height);
scrollFromBottom();
});
var go = 0;
var timeout = '';
function scrollFromBottom(){
clearTimeout(timeout);
var el = document.getElementById("newsdiv");
if(el.scrollTop >= el.scrollHeight-'150'){
el.scrollTop = 0;
};
el.scrollTop = el.scrollTop + speed;
if(go == 0){
timeout = setTimeout("scrollFromBottom()",60);
};
}
function stop(){
go = 1;
}
function startit(){
go = 0;
scrollFromBottom();
}
// -->
function window_onload() {
init();
}
// ]]>
</script>
<div id="newsdiv" onmouseout="startit();" onmouseover="stop();" >
<p id="newsdiv-p1" class="spacer">
</p>
<span id="NewsScroller1_lblNews"><a href='#' OnClick=javascript:window.open('newsDetail.aspx?NewsID=10','NewsDetail','width=800,height=600;toolbar=no;');><font face='verdana' size='2' color='#184D68'>Steve's Birthday</font><br><br><a href='#' OnClick=javascript:window.open('newsDetail.aspx?NewsID=15','NewsDetail','width=800,height=600;toolbar=no;');><font face='verdana' size='2' color='#184D68'>Our Anniversary</font><br><br><a href='#' OnClick=javascript:window.open('newsDetail.aspx?NewsID=14','NewsDetail','width=800,height=600;toolbar=no;');><font face='verdana' size='2' color='#184D68'>Jessie's Birthday</font><br><br></span>
<p id="newsdiv-p2" class="spacer"></p>
</div>
I am still trying to wrap my head on how this great forum works. Yesterday, I was able to see a button that says, "Add comment". Since today, I have not been able to see it. I guess my question is, how do you log back in so you are able to add comments, etc? Login appears to be cookie-driven which means that your priviledges disappear once you close the browser, no?
In this case, the error message ‘Object required’ means that variable el2 doesn't contain an HTMLElement object.
ID's of elements are case-sensitive, so you can't get the element
<p id="newsdiv-p1" class="spacer"></p>
using
var el2 = document.getElementById("newsDiv-p1");
Moreover, you can't access elements that have not been rendered yet. Put your function in an onload handler or after the markup.
BTW, the language attribute of the script element has been deprecated long ago.
Update: this piece of code
<script type="text/javascript" for="window" event="onload">
// <!CDATA[
return window_onload()
// ]]>
</script>
uses an IE-specific way to attach an event handler. Never use it!
Instead, use a DOM level 2 method or just
window.onload = window_onload;
You need to ensure that the DOM is ready before you start to interact with it.
I'd recommend using jQuery and wrapping your DOM-interactive code in the .ready() event hander, like this:
$(document).ready(function(){
init();
});
That way you can be sure that all your elements exist before you start to reference them, as stated in the jQuery API reference:
The handler passed to .ready() is
guaranteed to be executed after the
DOM is ready, so this is usually the
best place to attach all other event
handlers and run other jQuery code.
put your script tags after newsDiv. I think the problem arises because the html hasn't rendered yet.
Make sure that you have java script functions available in your page. Some times you get such errors when no method is accessible.
Related
I know this has been asked a lot on here, but all the answers work only with jQuery and I need a solution without it.
So after I do something, my Servlet leads me to a JSP page. My JS function should populate a drop down list when the page is loaded. It only works properly when the page is refreshed tho.
As I understand this is happening because I want to populate, using innerHTML and the JS function gets called faster then my HTML page.
I also get this error in my Browser:
Uncaught TypeError: Cannot read property 'innerHTML' of null
at XMLHttpRequest.xmlHttpRequest.onreadystatechange
I had a soulution for debugging but I can't leave it in there. What I did was, every time I opened that page I automatically refreshed the whole page. But my browser asked me every time if I wanted to do this. So that is not a solution that's pretty to say the least.
Is there something I could do to prevent this?
Edit:
document.addEventListener("DOMContentLoaded", pupulateDropDown);
function pupulateDropDown() {
var servletURL = "./KategorienHolen"
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
console.log(xmlHttpRequest.responseText);
let katGetter = JSON.parse(xmlHttpRequest.responseText);
JSON.stringify(katGetter);
var i;
for(i = 0; i <= katGetter.length -1; i++){
console.log(katGetter[i].id);
console.log(katGetter[i].kategorie);
console.log(katGetter[i].oberkategorie);
if (katGetter[i].oberkategorie === "B") {
document.getElementById("BKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie === "S") {
document.getElementById("SKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie ==="A") {
document.getElementById("ACat").innerHTML += "" + katGetter[i].kategorie + "</br>";
}
// document.getElementsByClassName("innerDiv").innerHTML = "" + katGetter.kategorie + "";
// document.getElementById("test123").innerHTML = "" + katGetter.kategorie + "";
}
}
};
xmlHttpRequest.open("GET", servletURL, true);
xmlHttpRequest.send();
}
It can depend on how + when you're executing the code.
<html>
<head>
<title>In Head Not Working</title>
<!-- WILL NOT WORK -->
<!--<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>-->
</head>
<body>
<p>Replace This</p>
<!-- Will work because the page has finished loading and this is the last thing to load on the page so it can find other elements -->
<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>
</body>
</html>
Additionally you could add an Event handler so when the window is fully loaded, you can then find the DOM element.
<html>
<head>
<title>In Head Working</title>
<script>
window.addEventListener('load', function () {
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
});
</script>
</head>
<body>
<p>Replace This</p>
</body>
</html>
Define your function and add an onload event to body:
<body onload="pupulateDropDown()">
<!-- ... -->
</body>
Script needs to be loaded again, I tried many options but <iframe/> works better in my case. You may try to npm import for library related to your script or you can use the following code.
<iframe
srcDoc={`
<!doctype html>
<html>
<head>
<style>[Style (If you want to)]</style>
</head>
<body>
<div>
[Your data]
<script type="text/javascript" src="[Script source]"></script>
</div>
</body>
</html>
`}
/>
Inside srcDoc, it's similar to normal HTML code.
You can load data by using ${[Your Data]} inside srcDoc.
It should work :
document.addEventListener("DOMContentLoaded", function(){
//....
});
You should be using the DOMContentLoaded event to run your code only when the document has been completely loaded and all elements have been parsed.
window.addEventListener("DOMContentLoaded", function(){
//your code here
});
Alternatively, place your script tag right before the ending body tag.
<body>
<!--body content...-->
<script>
//your code here
</script>
</body>
<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image);
var desc = document.getElementById(desc);
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiD.jpg"]
var descs = ["1", "2"]
var num = 0;
var total = images.length;
function clicked(){
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById(submit).onclick(clicked());
</script>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
</html>
The line "document.getElementById(submit).onclick(clicked());" throws an error
"ReferenceError: submit is not defined"
When I tried accessing buttons in general
[through getElementsByClassName & getElementsByTagName]
it gave an error of "ReferenceError: button is not defined"
Using strings in getElementById it throws the error "getElementById is null"
I found several questions and answers to this.
Only one of them I understood how to implement, due to the use of PHP and that being the error on most others. Other solutions I found involved errors numerically.
On this error I tried a fix of printwindow.document.getElementById(..etc
This gives me an error of "ReferenceError: printwindow is not defined"
Browsers run JavaScript as soon as possible in order to speed up rendering. So when you receive this code:
<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image); // Missing quotes, typo?
... in runs intermediately. There's no <foo id="image"> on page yet, so you get null. Finally, you get the rest of the page rendered, including:
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
It's too late for your code, which finished running long ago.
You need to bind a window.onload even handler and run your code when the DOM is ready (or move all JavaScript to page bottom, after the picture).
It should be document.getElementById('submit').onclick(clicked());
your must enclose the id you are searching for in quotes:
document.getElementById('ID_to_look_up');
You are executing javascript before your 'body' rendered. Thus document.getElementById("submit") would return null. Because there are no "submit" DOM element yet.
One solution is to move your javascripts under 'body', Or use JQuery with
$(document).ready(function() {
...
});
Your variable also has scope problem, your function cannot access variable declared outside this function with 'var' declaration. If you really need that variable, you should remove 'var' declaration.
A better way is to move all your variable inside clicked function. like following code
<html>
<head>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
<script type="text/javascript">
function clicked(){
var image = document.getElementById("image");
var desc = document.getElementById("desc");
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiE.jpg"];
var descs = ["1", "2"];
var num = 0;
var total = images.length;
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById("submit").onclick = clicked;
</script>
</html>
I am having a JavaScript code that is having a value in #message but i have not defined anywhere.
Does $("#message").html(result); is something inbuilt in Javascript?
I apologize if it is very basic and stupid question.
It is linked to my another question "
https://stackoverflow.com/questions/41745209/save-javascript-value-when-converting-speech-to-text-via-webkitspeechrecognition#
Complete Code
<!DOCTYPE html>
<html>
<head>
<script src="Content/SpeechScript.js"></script>
<title>Login Screen</title>
<meta charset="utf-8" />
</head>
<body >
<div id="results">
<span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<script type="text/javascript">
function Typer(callback) {
speak('Welcome ,Please Speak your CPR Number');
var srcText = 'WelcomeToDanske,PleaseSpeakyourCPR Numberwhat';
var i = 0;
debugger;
var result = srcText[i];
var interval = setInterval(function () {
if (i == srcText.length - 1) {
clearInterval(interval);
callback();
return;
}
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html(result);
debugger;
document.getElementById('user').innerHTML = result;
// var parent = document.getElementById('parentDiv');
// var text = document.createTextNode('the text');
// var child = document.getElementById('parent');
// child.parentNode.insertBefore(text, child);
// var div = document.getElementById('childDiv');
//var parent = document.getElementById('parentDiv');
//var sibling = document.getElementById('childDiv');
////var text = document.createTextNode('new text');
// //parent.insertBefore(result, sibling);
},
100);
return true;
}
function playBGM() {
startDictation(event);
}
Typer(function () {
playBGM();
});
// say a message
function speak(text, callback) {
var u = new SpeechSynthesisUtterance();
u.text = text;
u.lang = 'en-US';
u.onend = function () {
if (callback) {
callback();
}
};
u.onerror = function (e) {
if (callback) {
callback(e);
}
};
speechSynthesis.speak(u);
}
</script>
</div>
<div id="clockDisplay">
<span id="id1">Welcome:</span>
<table width="100%" border="1"><tr><td width="50%"> Username : </td><td><div id="message"></div></td></tr></table>
</body>
</html>
$("#message").html(result); is something inbuilt in Javascript?
No.
$ is a variable that is no part of the JavaScript spec, nor is it part of the common extensions to JS provided by browsers in webpages. It is commonly used by libraries such as PrototypeJS and jQuery. This particular case looks like jQuery, but you aren't including that library in your page.
Fist off, remember to include jQuery as script in your html document or $ will not be defined.
#message Refers to an element in your html document with the tag of id="message"
To get an element in jQuery, by id, you use this syntax: var Element = $("#ID");
So, to make sure your code works, ensure that both there is an element with the ID message, and a defined variable named result containing the html text to put into your element.
Since you want to append to <div id="clockDisplay"> <span id="user">Username :</span></div>, why not change it to:
<div id="clockDisplay">
<span id="user">Username :</span>
<div id="message"></div>
</div>
I have looked for duplicate questions, however many refer to adding data to XML
please forgive me if I have missed something here but I need some help
so far I have this:
html page
<!DOCTYPE html>
<html>
<head>
<title>Template</title>
<script type="text/javascript" src="script/controlpanelAdmin.js"></script>
<script type="text/javascript" src="script/controlpanelModerator.js"></script>
<script type="text/javascript" src="script/jquery-1.12.0.js"></script>
<link rel="stylesheet" href="script/css.css" />
</head>
<body>
<fieldset id="control_panel">
<legend>Control Panel</legend>
</fieldset>
<p id="content"> Content </p>
</body>
</html>
controlpanelAdmin.js
window.onload = function() {
var controlpanel = document.getElementById("control_panel");
var para = document.createElement("p");
var att = document.createAttribute("admin");
var br = document.createElement("br");
var txt = document.createTextNode("Admin Control Panel");
controlpanel.appendChild(para);
para.setAttribute("id", att);
para.appendChild(txt);
para.appendChild(br);
}
controlpanelModerator.js
window.onload = function() {
var controlpanel = document.getElementById("control_panel");
var para = document.createElement("p");
var att = document.createAttribute("mod");
var br = document.createElement("br");
var txt = document.createTextNode("Moderator Control Panel");
controlpanel.appendChild(para);
para.setAttribute("id", att);
para.appendChild(txt);
para.appendChild(br);
}
When the page loads, 'Admin Control Panel' is written into the fieldset tag
but is then replaced by: 'Moderator Control Panel'
I cannot for the life of me think how to append both lines (and maybe other data as well) into one element
When the page loads, 'Admin Control Panel' is written into the fieldset tag but is then replaced by: 'Moderator Control Panel'
That can't happen. Admin Control Panel should never appear in the page.
script/controlpanelAdmin.js loads. It causes a value to be assigned to window.onload.
script/controlpanelModerator.js loads. It causes that value to be overwritten with a new one.
The page finishes loading
The load event fires
The function defined in script/controlpanelModerator.js is called
Don't assign values to window.onload. Use addEventListener instead.
addEventListener("load", function () { ... });
You've got two onload functions competing. Can you merge them into one function?
I need to retrieve URL parameters (which I can do successfully) and based on one parameter, decide which iframe src to fill, then with other parameters auto fill the form that is created via the form src. First issue is that I can't keep the page from going into an infinite loop. It loads properly and shows the right iframe, but the infinite loop (load) needs to stop. Second, I can't get the other parameters to autofill the input values.
Here is the code. I hope you can help. Here is the code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/2000/REC- xhtml1-200000126/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Keep your jQuery up to date -->
<script type="text/javascript">
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
var test = urlParams["entry"];
var test2 = urlParams["test"];
function iframedirect(){
if (test=="sldk") {
document.getElementById("frame1").src = "http://na-sj09.marketo.com/lp/cochlearsandbox/UpgradeInterest_IFrameLandingPage.html";
var f1 = frames['frame1'].document.forms['mktForm_1108'];
f1.elements['FirstName'].value = test;
}else{
document.getElementById("frame1").src = "http://na-sj09.marketo.com/lp/cochlearsandbox/CAM-UpgradeInterestForm_iFrameLandingPage2ndOption.html";
}
}
</script>
</head>
<body id="bodyId" class="mktEditable" align="center" >
<iframe id="frame1" src="" onload="iframedirect()" height="750px" width="620px" scrolling="no" frameborder="0" marginwidth="0"></iframe>
</body>
</html>
The infinite loop is probably caused by the result of the function iframedirect().It changes the src of the iframe and triggers the onload event again and again.
You could use a variable to point out if the iframe has been loaded by iframedirect().
var test = urlParams["entry"];
var test2 = urlParams["test"];
var isLoadedByIFrameDirect = false;
function iframedirect() {
if(!isLoadedByIFrameDirect) {
if (test=="sldk") {
document.getElementById("frame1").src = "url1";
var f1 = frames['frame1'].document.forms['mktForm_1108'];
f1.elements['FirstName'].value = test;
}else{
document.getElementById("frame1").src = "url2";
}
isLoadedByIFrameDirect = true;
}
}
Okay, so the problem is that I created a sel-freferencing onload event. Bad idea. To solve the issue, I needed to remove the onload from the iframe element. I tried putting it in the Body before without luck. But I might have screwed it up, so don't ignore that option if you have a similar situation. I decided to do it with Javascript right after the function. If you are a novice, the difference between Javascript onload and HTML onload can be found here
W3Schools onload Event
I still have not solved the "autofilling iframe form from url parameter" portion of this problem. I will make an additional comment to this answer once I figure that out.
In any case, here is the code
function iframedirect() {
if(!isLoadedByIFrameDirect) {
if (test=="sldk") {
document.getElementById("frame1").src = "http://na- sj09.marketo.com/lp/cochlearsandbox/UpgradeInterest_IFrameLandingPage.html";
var f1 = frames['frame1'].document.forms['mktForm_1108'];
f1.elements['FirstName'].value = test;
}else{
document.getElementById("frame1").src = "http://na-sj09.marketo.com/lp/cochlearsandbox/CAM-UpgradeInterestForm_iFrameLandingPage2ndOption.html";
}
isLoadedByIFrameDirect = true;
}
}
window.onload = iframedirect;