How do I clear inner HTML - javascript

I've been fiddling with this for a while but it won't work and I can't figure out why. Please help. Here is what I have:
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function clear() {
document.getElementById("goy").innerHTML = "";
}
</script>
</body>
</html>
The mouseover works and displays the text in the div, but when I move the mouse out of the h1 tag, the text stays there and I don't know why, help would be appreciated.

The problem appears to be that the global symbol clear is already in use and your function doesn't succeed in overriding it. If you change that name to something else (I used blah), it works just fine:
Live: Version using clear which fails | Version using blah which works
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 onmouseover="go('The dog is in its shed')" onmouseout="blah()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function blah() {
document.getElementById("goy").innerHTML = "";
}
</script>
</body>
</html>
This is a great illustration of the fundamental principal: Avoid global variables wherever possible. The global namespace in browsers is incredibly crowded, and when conflicts occur, you get weird bugs like this.
A corollary to that is to not use old-style onxyz=... attributes to hook up event handlers, because they require globals. Instead, at least use code to hook things up: Live Copy
<html>
<head>
<title>lala</title>
</head>
<body>
<h1 id="the-header">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
// Scoping function makes the declarations within
// it *not* globals
(function(){
var header = document.getElementById("the-header");
header.onmouseover = function() {
go('The dog is in its shed');
};
header.onmouseout = clear;
function go(what) {
document.getElementById("goy").innerHTML = what;
}
function clear() {
document.getElementById("goy").innerHTML = "";
}
})();
</script>
</body>
</html>
...and even better, use DOM2's addEventListener (or attachEvent on IE8 and earlier) so you can have multiple handlers for an event on an element.

const destroy = container => {
document.getElementById(container).innerHTML = '';
};
Faster previous
const destroyFast = container => {
const el = document.getElementById(container);
while (el.firstChild) el.removeChild(el.firstChild);
};

The h1 tags unfortunately do not receive the onmouseout events.
The simple Javascript snippet below will work for all elements and uses only 1 mouse event.
Note: "The borders in the snippet are applied to provide a visual demarcation of the elements."
document.body.onmousemove = function(){ move("The dog is in its shed"); };
document.body.style.border = "2px solid red";
document.getElementById("h1Tag").style.border = "2px solid blue";
function move(what) {
if(event.target.id == "h1Tag"){ document.getElementById("goy").innerHTML = "what"; } else { document.getElementById("goy").innerHTML = ""; }
}
<h1 id="h1Tag">lalala</h1>
<div id="goy"></div>
This can also be done in pure CSS by adding the hover selector css property to the h1 tag.

Take a look at this. a clean and simple solution using jQuery.
http://jsfiddle.net/ma2Yd/
<h1 onmouseover="go('The dog is in its shed')" onmouseout="clear()">lalala</h1>
<div id="goy"></div>
<script type="text/javascript">
$(function() {
$("h1").on('mouseover', function() {
$("#goy").text('The dog is in its shed');
}).on('mouseout', function() {
$("#goy").text("");
});
});

Related

Can't call function from body onload (uncaught reference error: start is not defined) javascript

I have a body onload calling a function in javascript. I Have tried many things, but the console just prints to the error log: uncaught reference error: start is not defined. I think it might be a malfunction, please notify me if it works for you. My code is as follows:
<!DOCTYPE html>
<html>
<head>
<title>Monster Invasion</title>
<script type="javascript">
var hur;
var monsters = 10;
var objective = false;
var health = 100;
var damage = 30;
var sheild = false;
var ea = 1;
function start() {
setTimeout(hurt,4000)
}
function hurt() {
var newhelth = health - damage;
health = newhelth;
document.getElementById("healtw").innerHTML = health;
start();
}
function kill() {
if(monsters > 0) {
monsters--;
document.getElementById("monster1").src="dead.jpg"
setTimeout(next,2000)
}else {
objective = true;
document.location="endoflevel.html";
}
}
function next() {
document.getElementById("monster1").src="monster.jpg"
}
}
</script>
</head>
<body onload="start()">
<p id="healtw"></p>
<embed src="guide_first_level.mp3" type="audio/mp3" hidden="true" autostart="true">
<a id="st" onclick="kill()"><img id="monster1" src="monster.jpg"></a>
<p id="ada"></p>
Activate sheild
</body>
</html>
your script type is wrong.
try like this
<script type="text/javascript">
</script>
However, you don't need to mention script type. just use a plain script tag.
like this
<script>
</script>
One more thing to add that before the end of the script tag, you gave an extra }.
just remove it
function next() {
document.getElementById("monster1").src="monster.jpg"
}
} // <-- just remove this bracket
</script>
Well for some of you, who are using external js file, please just check to see whether you linked your file or not :)... because I had the same error but as I looked through my code ..I hadn't linked the file then!
just in case you came here looking for an answer too!
There are two problems with your code.
javascript is not a valid type for the script in the browser. Browsers know text/javascript, but not just javascript, that is why your code is not being executed. Change the type attribute or remove it at all (for text/javascript is the default value).
You have an extra bracket } at the end of the code. Remove it and your code will work fine.
There are 3 errors:
Correct the type of your script tag
There is an extra } at the end of your code
Instead of using onload() for body tag, you should better use window.onload as follows in order to make sure your start() function is run once document is ready:
...
<head>
<title>Monster Invasion</title>
<script type="text/javascript">
window.onload = function(){
// Put all your code here
// And at the end run start() function
start();
}
</script>
</head>
<body>
...

Call two different functions on same onclick event in javascript one after another

I have one div content whose height should be 300px when i click on another div name button.
But how can i reset the height, when again clicked on button div?
Here is the javascript code for reference:
function chk()
{
var x = document.getElementById('content').style.height = '300px';
}
This is the HTML code
<div id="content">
This is dummy text.
</div>
<div id="button" onclick="chk()">
click to read
</div>
When button div is click content height increases, but how can i reduce the height by clicking on same div with same onclick event?
Use CSS:
#content {
height: auto;
}
#content.expand {
height: 300px;
}
In your script:
function chk()
{
var node = document.getElementById('content');
node.classList.toggle('expand');
}
This keeps the state local to the element you're working on, which makes for more flexible code.
See also: classList API
You could use a flag:
var isSet = false:
function chk(){
if(!isSet) {
var x = document.getElementById('content').style.height = '300px';
isSet = true;
}
else {
// some other computation
isSet = false;
}
}
Either a flag
var flag;
function chk() {
var height = flag ? '0px' : '300px';
document.getElementById('content').style.height = height;
flag = !flag;
}
or by checking the current height
function chk() {
var currHeight = document.getElementById('content').style.height;
var setHeight = height == '300px' ? '0px' : '300px';
document.getElementById('content').style.height = setHeight;
}
If you are just learning HTML, CSS, and JavaScript you should start by making your code more clear.
// HTML should look more like
<!DOCTYPE html>
<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' />
<style type='text/css'>
#import 'common.css'; #import 'page.css';
</style>
</head>
<body>
<div id='content'>
This is dummy text.
</div>
<input type='button' value='click to read' id='button' />
<script type='text/javascript' src='common.js'></script>
<script type='text/javascript' src='page.js'></script>
</body>
</html>
Notice, your button should be a button, not a div. XHTML is more expandable for scraping and XSLT, and will work on HTML pages, but not the other way around.
// learn to keep your JavaScript separate pages for caching - common.js
//<![CDATA[
// reduce objects to smaller variables and never use `document.getElementById()`
var doc = document, bod = doc.body;
function E(e){
return doc.getElementById(e);
}
//]]>
// page.js
//<![CDATA[
var button = E('button');
/* The self-executing Anonymous Function below creates scope for `var test` and
returns an unexecuted function you can call later. Note that a function is
basically a variable that if you add `()` to will execute. */
var changeHeight = (function(){
var test = false;
return function(id, before, after){
E(id).style.height = test ? before : after;
test = !test;
}
})();
/* This is a backward compatible way of creating an `onclick` function, unlike
`.addEventListener()` and `attachEvent()`, this is assignment, so it will
write over your last `onclick` assiged to this specific Element */
button.onclick = function(){
changeHeight('content', '20px', '300px');
}
// To combat the comment above you could do something like this:
/*
button.onclick = function(){
changeHeight('content', '20px', '300px');
}
function anotherFunction(){
console.log('wow');
}
var before = button.onclick;
button.onclick = function(){
if(before)before();
anotherFunction();
}
*/
/* An executed function, would execute before the event is handled. The only
thing that is automatically passed to your variable function or Anonymous
Function is the Event Object. In this case it is not necessary, because we
are not accessing the Event Object. */
//]]>

Switching backgrounds, while switching text

I was able to make the text loop infinitely and the body color change once:
<?php?>
<style type="text/css">
<!--
header{background-color:orange;}
#color1{background-color:red;}
#color2{background-color:green;}
#color3{background-color:blue;}
-->
</style>
<script type="text/javascript">
<!--
var flip = (function() {
var flip = ['_addText1','_addText2','_addText3'];
var count = -1;
return function() {
return flip[++count % flip.length];
}
}());
-->
</script>
<body id="color1">
<header onclick="document.getElementById('click').innerHTML = flip(); document.getElementById('color1').setAttribute('id', 'color2');">
<h1>StaticText<a id="click">_ThisWillChange</a></h1>
<p>Click anywhere in the header to change the text above.<br />
This will also change the body color.</p>
</header>
</body>
<?php?>
The first problem is; if I add more color changes to the 'onclick' attribute it stops working all together. Basically I want the color to loop with the text:
document.getElementById('color2').setAttribute('id', 'color3');
document.getElementById('color3').setAttribute('id', 'color1');
The second problem is that I'm not really 'fluent' in javascript. I'm actually lucky I figured out this much to be honest.
I'm sure there's a way to put it all into the javascript (to keep my HTML clean), but I don't know how.
Any help would be most appreciated! Thanks in advance...
Why do you want to change the id of the element if you are so keen to set the color.
You can just the class on the body element which should get the work done for you.
Secondly it's a bad practice to bind events inline. Use javascript to bind the events as well.
<body id="color1" class="color1">
This is one way of writing the code.
Code
var header = document.getElementsByTagName('header')[0];
header.addEventListener('click', function () {
var body = document.getElementById('color1');
document.getElementById('click').innerHTML = flip("text");
body.className = flip("color");
});
var flip = (function () {
var flip = ['_addText1', '_addText2', '_addText3'],
colors = ["color1", "color2", "color3"];
var count = -1,
colorCount = -1;
return function (arg) {
if(arg === 'text')
return flip[++count % flip.length];
if(arg === 'color')
return colors[++colorCount % colors.length];
}
})();
HTML
<body id="color1" class="color0">
<header>
<h1>StaticText<a id="click">_ThisWillChange</a></h1>
<p>Click anywhere in the header to change the text above.
<br />This will also change the body color.</p>
</header>
</body>
CSS
header {
background-color:orange;
}
.color0 {
background-color:yellow;
}
.color1 {
background-color:red;
}
.color2 {
background-color:green;
}
.color3 {
background-color:blue;
}
Check Fiddle

How to run and display processing code (currently in part of the document.body) in an html canvas?

NOTE: I know I can import .pde files but I need to run code on screen so I will not be using this.
My three following attempts failed. I do not know which one was closer to achieving and I do not prefer one as long as it produces desired result. Appreciate the help by helping me get any of the attempts working/suggesting a new one.
1ST ATTEMPT) - use getText function written below but then some text that is not code can be found in the resulting jscode variable and thus the processing instance does not work.
function getText(n) {
var s = [];
function getStrings(n, s) {
var m;
if (n.nodeType == 3) { // TEXT_NODE
s.push(n.data);
}
else if (n.nodeType == 1) { // ELEMENT_NODE
for (m = n.firstChild; null != m; m = m.nextSibling) {
getStrings(m, s);
}
}
}
getStrings(n, s);
var result = s.join(" ");
return result;
}
var processingCode = getText(document.body)
processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = document.getElementById("mysketch");
var processingInstance = new Processing(canvas, jsCode);
....
<span class="sketch">
<canvas id="mysketch"></canvas>
</span>
2ND ATTEMPT) Same as above but added a tag with id="all_processing_code" but couldn't figure out how to get the text within anyway. This did not work:
var processingCode = getText(document.getElementbyId(all_processing_code));
3RD ATTEMPT) Removed getText and tried to use JQuery text() to isolate the code. Was having trouble mixing JS and Jquery though. Tried different stuff and none worked. What would be appropriate way to mix it in? What script type should I use? This was confusing.
<script type="text/jquery">
var processingCode = $('#all_processing_code').text();
//processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = $.Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = $(#'mysketch');
var processingInstance = new $.Processing($('canvas'), $('jsCode'));
}
</script>
First, check if your processing code is wrapped by an html element (like a div or something else) with an id. If it isn't, please do it!
For exemple:
<div id="mycode">
void setup() {
background(0);
}
</div>
After this, check if you have the getProcessingSketchId() function declared in your code. Processing IDE in JavaScript mode already exports html files with that function. If there isn't, please declare it inside your <head>:
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
You can include JQuery from google api including this line in your html before you use JQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
Assuming that you want to run your processing code when the page just has loaded, just append this code after the getProcessingSketchId() declaration.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
You can create this code inside any other <script type="text/javascript">.
At the end, you will have something like this:
<html>
<head>
<!-- Your title, meta tags, stylesheet and all other stuff here -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
</head>
<body>
<div id="mycode">
void setup() {
background(0);
}
</div>
</body>
</html>

Javascript Onclicks not working?

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}
You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);
Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'

Categories

Resources