Javascript document.getElementById doesn't seem to work - javascript

I have the following code, and the javascript console in chrome says "Can't read innerHTML property of null. Why does document.getElementById('display') turn up empty handed?
<!DOCTYPE html>
<html>
<head>
<title>Chat 3</title>
<script type="text/javascript">
function showmsg(str){
var display = document.getElementById('display');
display.innerHTML += "<p>" + str + "</p>";
}
if("WebSockets" in window){
pass;
}else{
showmsg("Your browser doesn't support WebSockets. Try Google Chrome.");
}
</script>
<style type="text/css">
#username {
padding: 0px;
margin: 0px;
height: 26px;
width: 400px;
}
/* ADDED container div that wraps onlineusers and display */
#container {
margin: 10px 0;
}
/* use float: left to put them side-by-side */
#display {
padding: 0px;
margin: 0px;
border-style: solid;
border-width: 1px;
overflow: auto;
height: 400px;
width: 400px;
float: left;
}
#onlineusers {
padding: 0px;
margin: 0px;
height: 400px;
width: 200px;
border-style: solid;
border-width: 1px;
float: left;
}
/* Added container2 to wrap inputline and sendbutton */
#container2 {
margin: 10px 0;
}
#inputline {
padding: 0px;
margin: 0px;
height: 26px;
width: 350px;
float: left;
}
#sendbutton {
padding: 0px;
margin: 0px;
height: 30px;
width: 50px;
float: left;
}
/* this is a well used "hack". */
.clearfix {
clear: both;
}
</style>
</head>
<body onload="document.getElementById("username").focus()">
<input type="text" id="username" />
<div id="container">
<div id="display"></div>
<div id="onlineusers"></div>
<div class="clearfix"></div>
</div>
<div id="container2">
<input type="text" id="inputline" length="55" />
<input type="button" id="sendbutton" value="Send" />
</div>
</body>
</html>

Move your script-section down to the bottom of the page. Otherwise it is executed before the page has been loaded.
Btw: Putting scripts at the bottom of your page is even a "best practice" and recommended by Google, Yahoo & Co

You're calling showmsg before the whole page (and hence the display div) is loaded. Hence the error. Call it from onload and it'll work.
Add this function to the <head>
function handleLoad()
{
document.getElementById("username").focus()
if("WebSockets" in window){
pass;
}else{
showmsg("Your browser doesn't support WebSockets. Try Google Chrome.");
}
}
and call it from onload
<body onload="handleLoad()">

Put your script tag at the end of the document:.
In your case the page has not been completely parsed into DOM tree, but your script executes anyway:
<body onload="document.getElementById('username').focus()">
<input type="text" id="username" />
<div id="container">
<div id="display"></div>
<div id="onlineusers"></div>
<div class="clearfix"></div>
</div>
<div id="container2">
<input type="text" id="inputline" length="55" />
<input type="button" id="sendbutton" value="Send" />
</div>
<script type="text/javascript">
function showmsg(str){
var display = document.getElementById('display');
display.innerHTML += "<p>" + str + "</p>";
}
if("WebSockets" in window){
pass;
}else{
showmsg("Your browser doesn't support WebSockets. Try Google Chrome.");
}
</script>
</body>
This is also considered a good practice for performance reasons:
http://developer.yahoo.com/performance/rules.html#js_bottom

Related

Text align not working under div using javascript print button

I have placed a div on html page and text under it with center align. A custom java script button is also placed for printing under the div content. When i press a button it previews the text with left align. Please anyone guide how to set or apply my css or style to this div for center align. Complete html code is following written in asp.net. Thanks in advance
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="margin_issue.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1">
<div id="DivForPrint" class="myDivToPrint" style="border: 1px dotted black; text-align: right; padding-left: 250px; width: 600px">
<span style="font-size: 10pt; font-weight: bold; font-family: Arial">Hello,
<br />
This is <span style="color: #0090CB">Mudassar Khan</span>.<br />
Hoping that you are enjoying my articles!</span>
</div>
<br />
<input type="button" value="Print" onclick="javascript: printDiv('DivForPrint')" style="width: 80px; height: 30px;" />
</form>
</body>
</html>
<script type="text/javascript">
function printDiv(divID) {
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divElements + "</body>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}
</script>
EDIT
Your code is working awesome according to my need. I have little observations that i need to understand. I have copied two portions from your code, CSS and javascript. Please see below.
<style>
.page_size { border: 1px dotted black; text-align: left; width: 800px; height: 950px; }
.instr_date { text-align: right; padding-right: 0px; padding-top: 40px;}
.benef_name {text-align: left; padding-left: 50px; padding-top: 50px; }
.leftDiv { border: 1px dotted black; text-align: left; padding-left: 0px; }
</style>
Javascript
function printDiv(divID) {
var div = document.getElementById(divID).outerHTML;
var mywindow = window.open('', 'Print Contents');
mywindow.document.write('<html><head><title>Print Contents</title>');
mywindow.document.write('<style> .page_size {border: 1px dotted black; text-align: left; width: 800px; height: 950px; }</style>');
mywindow.document.write('<style> .instr_date {text-align: right; padding-right: 0px; padding-top: 40px; }</style>');
mywindow.document.write('<style> .benef_name { text-align: left; padding-left: 50px; padding-top: 50px; }</style>');
mywindow.document.write('<style> .leftDiv {border: 1px dotted black; text-align: left; padding-left: 0px; }</style>');
mywindow.document.write('</head><body>');
mywindow.document.write(div);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10
mywindow.print();
mywindow.close();
}
</script>
You can see above i have written two css files, one is normal under style tag and other is injected to java script and i am writing many lines for css in java script. Now i have two simple questions following:-
1- Cannot we write one css which should effect everywhere?.
2- If the answer of first question is no: then how can i avoid writing multiple css lines in java script.
Many thanks.
Have a look at the following to point you in the right direction. Instead of changing the entire page and then reverting it, open a new window to do the print. This will stop any potentially nasty bugs appearing when revert the page. Also having 2 different class names for non-print and print DIVs may be useful. You can put these in an external CSS file and then add the CSS link to the new window aswell.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>
</title>
<style>
.myDiv {
border: 1px dotted black; text-align: right; padding-left: 250px; width: 600px;
}
</style>
<script type="text/javascript">
function printDiv(divID) {
var div = document.getElementById(divID).outerHTML;
var mywindow = window.open('', 'Print Contents');
mywindow.document.write('<html><head><title>Print Contents</title>');
mywindow.document.write('<style>.myDiv {border: 1px dotted black; text-align: center; width: 100%;}</style>');
mywindow.document.write('</head><body>');
mywindow.document.write(div);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10
mywindow.print();
mywindow.close();
}
</script>
</head>
<body>
<form id="form1">
<div id="DivForPrint" class="myDiv">
<span style="font-size: 10pt; font-weight: bold; font-family: Arial">Hello,
<br />
This is <span style="color: #0090CB">Mudassar Khan</span>.<br />
Hoping that you are enjoying my articles!</span>
</div>
<br />
<input type="button" value="Print" onclick="javascript: printDiv('DivForPrint')" style="width: 80px; height: 30px;" />
</form>
</body>
</html>

Trying to change colour of a button to show which images is displayed with javascript

I'm trying to change colour of a button to show which images is displayed with JavaScript. Something similar to :Active in CSS. I've been looking for hours, I've managed to change just about every other element on the page except for the one I actually want to change, all I need is to change the background color of the clicked button and then revert back to original color a different button is clicked. Any help would be much appreciated.
<! doctype html>
<html>
<head>
<title>Task 2</title>
<!--styles-->
<style>
body {
margin: 0;
background-color: mediumpurple;
}
header {
margin: auto;
width: 90%;
background-color: orangered;
height: 50px;
text-align: center;
}
#content {
width: 80%;
background-color: green;
margin: auto;
}
nav {
float: left;
background-color: greenyellow;
width: 30%;
height: 750px;
text-align: center;
}
#pictureFrame {
float: left;
width: 70%;
height: 750px;
background-color: deeppink;
}
footer {
margin: auto;
width: 90%;
background-color: orangered;
height: 50px;
text-align: center;
clear: both;
}
.button {
margin-top: 100px;
background-color: white;
border-radius: 20px;
width: 70%;
height: 75px;
}
#img {
margin-top: 19%;
margin-left: 35%;
width: 300px;
height: 300px;
}
</style>
<script type="text/javascript">
function pic1() {
document.getElementById("img").src = "images/starbucks.png";
}
function pic2() {
document.getElementById("img").src = "images/muffin.png";
}
function pic3() {
document.getElementById("img").src = "images/costa.png";
}
</script>
</head>
<body>
<header>
<h1>Coffee</h1>
</header>
<section id="content">
<div id="pictureFrame">
<img src="" id="img" />
</div>
<nav>
<button id="button1" class="button" onclick="pic1()">Starbucks</button>
<br/>
<br/>
<button id="button2" class="button" onclick="pic2()">Muffin Break</button>
<br/>
<br/>
<button id="button3" class="button" onclick="pic3()">Costa</button>
</nav>
</section>
<footer>
<h1>This is a footer</h1>
</footer>
</body>
</html>
By clicking on each button simply change the background of that button with style.background='color'. Also reset the color of other two buttons. Simply create a function to reset the background color.
<script type="text/javascript">
function reset(){
document.getElementById("button1").style.background='white';
document.getElementById("button2").style.background='white';
document.getElementById("button3").style.background='white';
}
function pic1() {
document.getElementById("img").src = "images/starbucks.png";
reset();
document.getElementById("button1").style.background='red';
}
function pic2() {
document.getElementById("img").src = "images/muffin.png";
reset();
document.getElementById("button2").style.background='red';
}
function pic3() {
document.getElementById("img").src = "images/costa.png";
reset();
document.getElementById("button3").style.background='red';
}
</script>
Fiddle : https://jsfiddle.net/tintucraju/6dkt0bs2/

Save user input to paragraph

I'm trying to create a program where the user will input some text in a field and when pressing "Start" the text will go to a paragraph but it will be shown backwards.
Trying to do this with Html,jquery and Css.
How can I do this?
Here's the Html:
<!DOCTYPE html>
<html id="head">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="BackTalk.js"></script>
<link rel="stylesheet" type="text/css" href="BackTalk.css">
<title>BackTalk</title>
</head>
<body id="body">
<div id="Main">
<form>
<input id="input" type="number" value="Start">
<button id="input2" onclick="">Start</button>
</form>
</div>
<form id="frm">
<p id="para"></p>
</form>
</body>
</html>
And the $/javascript (Main part I need help with as you can see):
$(document).ready(function () {
$('#input2').click(function () {
});
});
Css (Don't know if needed):
#head {
}
#body {
background-image: url('stardust.png');
}
#Main {
width: 230px;
padding: 10px;
border: 1px double #ffffff;
border-radius: 10px;
margin: auto;
}
#frm {
width: 230px;
height: 500px;
padding: 10px;
border: 1px double #ffffff;
border-radius: 10px;
margin: auto;
}
#input {
border-radius: 10px;
}
#input2 {
border-radius: 10px;
}
Try this http://jsfiddle.net/Tushar490/th778nfs/
$('#input2').click(function () {
var value=$('#input').val();
console.log($('#para').text(value.split("").reverse().join("")));
});
Not sure if this is exactly what you're looking for:
$(document).ready(function () {
$('#startbutton').click(function () {
$('#para').text($('#input').val().split('').reverse().join(''));
});
});
JSFiddle

disable jQuery removing javascript tags

Best all,
I'm trying to debug our CMS (what is mostly AJAX) but jQuery removes all the script tags, what makes me unable to debug the JavaScript, how do I disable this behaviour?
I thought I would find it after a simple Google search but no success :(
Thank you,
EDIT
my Page before:
<script>
jQuery(function(){
inter = null;
jQuery('#parse').click(function(){
jQuery('#answer').load(f(),{"POST":jQuery("#POST").val(),"start":((jQuery('#start').val()-1)*10)},function(){
alert("Burrrnnnnnnn")
console.log("Laten we is kijken: " + inter);
clearInterval(inter);
});
inter = setInterval(function(){
jQuery.getJSON("/googlemonster/backend/status-test",function(json){
setProgressBar(json);
});
},200);
return false;
});
});
function
function setProgressBar(obj){
var g;
jQuery("#progress-bar,#progress-text-alt-wrapper").animate({"width":(((g=obj["%"])==0?1:g)*2) + "px"},{queue:false});
jQuery("#progress-text,#progress-text-alt").text(obj["%"] + "% " + obj["status"]);
}
</script>
<style>
#progress-text-alt-wrapper {
height: 30px;
position: absolute;
z-index: 2;
width: 1%;
overflow: hidden;
}
#progress {
border: solid black 1px;
padding: 1px;
text-align: center;
height: 20px;
width: 200px
}
#progress-bar {
background-color: green;
width: 1%;
height: 100%;
}
.progress-bar-text {
padding-top: 3px;
text-align: center;
width: 200px;
position: absolute;
}
#progress-text {
color:green;
}
#progress-text-alt {
color:#eee;
}
</style>
Query:
<input id="POST" type="text" />
<br>
Pagina
<input value="1" id="start"
type="number" />
<br>
<button id="parse">Look</button>
<div>
<div id="progress">
<div id="progress-text-alt-wrapper">
<div class="progress-bar-text" id="progress-text-alt">0% Nothing</div>
</div>
<div class="progress-bar-text" id="progress-text">0% Nothing</div>
<div id="progress-bar"></div>
</div>
</div>
<div id="answer"></div>
The page after
<style>
#progress-text-alt-wrapper {
height: 30px;
position: absolute;
z-index: 2;
width: 1%;
overflow: hidden;
}
#progress {
border: solid black 1px;
padding: 1px;
text-align: center;
height: 20px;
width: 200px
}
#progress-bar {
background-color: green;
width: 1%;
height: 100%;
}
.progress-bar-text {
padding-top: 3px;
text-align: center;
width: 200px;
position: absolute;
}
#progress-text {
color:green;
}
#progress-text-alt {
color:#eee;
}
</style>
Query:
<input id="POST" type="text">
<br>
Pagina
<input value="1" id="start" type="number">
<br>
<button id="parse">Look</button>
<div>
<div id="progress">
<div id="progress-text-alt-wrapper">
<div class="progress-bar-text" id="progress-text-alt">0% Nothing</div>
</div>
<div class="progress-bar-text" id="progress-text">0% Nothing</div>
<div id="progress-bar"></div>
</div>
</div>
<div id="answer"></div>
You are right – it is a feature of jQuery to strip out script tags. You need to use the basic JavaScript methods instead.
See: Can't append <script> element
Scripts will be evaluated first, and then discarded.
http://api.jquery.com/append/
after some research I finnaly could fix the problem thanks to the guys here,
I made a little plugin for jQuery for it, now the script tags are not getting, removed but executed.
(function($){
$.fn.loadDebuggable = function(url){
data = typeof(arguments[1]) == "object"?arguments[1]:{};
success = arguments[2]||typeof(arguments[1]) == "function"?arguments[1]:function(){};
return $.ajax(url,{
"context":this,
"success":[function(data){
var div = document.createElement('DIV');
div.innerHTML = data;
this[0].innerHTML = "";
while (div.firstChild)
{
this[0].appendChild(div.firstChild);
div.removeChild(div.firstChild);
};
},success],
"type":"GET",
"data":data
});
}
})(jQuery);
Thanks,

Can't get JQuery UI Selectable to work at all

I've been having some trouble getting JQuery UI selectable to work with my site. I'm still very new to coding and I'm not sure what I'm doing wrong. I've searched for relevant questions and haven't been able to find any that let me figure it out.
I'm trying to create whats essentially a glorified label maker for work, and would like to be able to select cells in a grid using a mouse "lasso." But for some reason, I can't get selectable to work at all.
Here is the js:
$('document').ready(function() {
for (i=0; i<117;i++) {
$('#plateActual').append('<div class="cell"/>');
}
$('#plateActual').selectable();
});
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="style.css" />
<link type="text/css" href="css/smoothness/jquery-ui-1.8.21.custom.css" rel="Stylesheet" />
<script type="text/javascript" src="js/jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
</head>
<body>
<div id="wrapper">
<div id="navbar">
</div>
<div id="controlPanel">
<p>test<br>test<br>test<br>test<br>test<br>test<br></p>
<p>test<br>test<br>test<br>test<br>test<br>test<br></p>
<p>test<br>test<br>test<br>test<br>test<br>test<br></p>
<p>test<br>test<br>test<br>test<br>test<br>test<br></p>
<p>test<br>test<br>test<br>test<br>test<br>test<br></p>
<p>test<br>test<br>test<br>test<br>test<br>test<br></p>
</div>
<div id="plateEditor">
<div id="plateActual">
</div>
</div>
<div id="bottom">
</div>
</div>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.21.custom.min.js"></script>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
</body>
Here is the CSS:
body {
margin: 0px auto;
padding: 0;
}
p {
color: yellow;
}
#wrapper {
border: 1px dotted black;
width: 980px;
margin: 0px auto;
padding: 0;
}
#navbar {
width: 980px;
background: black;
height: 50px;
position: fixed;
margin: 0;
padding: 0;
top: -10px;
}
#controlPanel {
width: 250px;
background-color: red;
float:left;
top: 100px;
margin-bottom: 0;
}
#plateEditor {
position: relative;
overflow: auto;
width: 730px;
float:right;
top: 100px;
margin-bottom: 0;
margin-top: 150px;
}
#plateActual {
border: 1px solid;
width: 403px;
height: 279px;
margin: 0px auto;
pading: 0;
}
#bottom {
width: 980px;
height: 30px;
background:green;
clear: both;
bottom: 0;
margin: 0px auto;
padding: 0;
}
.cell {
float: left;
width: 29px;
height: 29px;
border: 1px dotted;
}
I apologize if my code is messy and unorganized. I am still figuring out how to best keep it organized and generally write it in an acceptable fashion. Thanks a lot for your help.
Update: I've made the change Ando suggested, but I'm still unable to get selectable to work. I've tried changing #plateActual to an ol or ul and appending li.cell instead but that did not work either.
I was wondering if the reason is my css is somehow interfering with it, but I'm not sure how to fix that without destroying the formatting.
The element returned by append will be the element to which the add is performed - in your case plateActual- so you will be adding the cell class to the wrong element.
When you append the cells - you use $('<div/>') - which will translate to "get the elements of type '<div/>' from the dom and move them inside my 'plateActual' element" - you should add without $ as you are creating an element that does not yet exist.
Something like this should work (http://jsfiddle.net/k3YJY/):
for (var i=0; i<5;i++) {
$('#plateActual').append('<div class="cell"/>');
}

Categories

Resources