store the 'this' object in an onclick attribute - javascript

What I ultimately want is to retrieve the innerHTML of the example script below (the html is to be put in a database). It must include the onclick events also. However in the generated HTML there is no onclick event available.
<html>
</head>
<script>
function test() {
this.goodbye="goodbye!";
this.elem=document.createElement('div');
this.elem.style.border='1px solid #888888';
this.elem.textContent="hello";
this.elem.style.cursor='pointer';
var that=this;
this.elem.onclick=function(){that.say_goodbye();}
document.getElementsByTagName('body')[0].appendChild(this.elem);
}
test.prototype.say_goodbye=function(blockid) {
this.elem.textContent=this.goodbye;
}
</script>
</head>
<body>
<script>var obj = new test();</script>
get html
</body>
</html>
the line of importance is thus:
this.elem.onclick=function(){that.say_goodbye();}
I tried to add it as attribute like:
this.elem.setAttribute('onclick',that.say_goodbye.bind(that));
But is doesn't work. When I click the link in the given code the browser alerts:
<div> onclick="function(){[native code]}" ..... </div>
In this case the HTML now has an 'onclick' event but contains '[native code]' as action.
Anyone an idea on how to make the code work?

The reason you get this is that attribute value is text always and you are trying to put object into it (functions are objects). This case you should rather use this.elem = that.say_goodbye.bind(that).

Related

Passing HTML value to embedded script

So I have a HTML file with an embedded script. A Java application sends a value to this HTML file. Now I wonder how to pass this value from the HTML down to the script. Is this even possible?
Here is the simplified HTML file with my approach:
<html>
<body>
<div id="test">
[VALUE_FROM_BACKEND] // prints "let valueFromBackend = 1234"
</div>
<script>
console.log(document.getElementById('test').value);
// should return: let valueFromBackend = 1234;
// actually returns: undefined
</script>
</body>
</html>
Unfortunately, I can't pass the value from the Java application directly to the script. I got the above approach from here, but this doesn't work.
Other solutions only focus on getting values from remote HTML pages, declaring the HTML files's source in the script tag. But since it is an embedded script here, this also seems not to work.
Does anyone know how to deal with the situation? Help will be much appreciated.
Only HTML input elements have a value in javascript. A div cannot have a value, which is why your code returns undefined.
To access the text inside a regular HTML element, such as a div, use element.innerText instead.
Here is a working code snippet you can try out:
console.log(document.getElementById('test').innerText);
<div id="test">
let valueFromBackend = 1234
</div>
As you want to get value of a div element, so the syntax is:
document.getElementById('test').innerHTML
Remember that getElementById().value works for input and use getElementById().innerHTML for elements like div

Take a string and use it as pure HTML?

Lets say I have a string called Test, and its value is:
<img src=test.gif></img>
<p> Testing 123 </p>
Is it somehow possible to use it as code since the HTML isn't compiled?
Edit: I tried this and it didn't work.
<body>
<p id="myText" onload="HTMLThing()"> Soon. </p>
</body>
<script>
var testString = "<img src=test.gif></img><p> Testing 123 </p>"
function HTMLThing(){
document.getElementById("myText").innerHTML=testString;
}
</script>
I don't know which language you are using, but certainly you can open a file(with .html extension) and dump the string to that file. Later, when you open the HTML file, you will get the rendered web page.
But be sure about the directory in which you create that file, should also contain the image, or you can change the image's location in the string.
On your page you can create HTML element and give it some ID, e.g. "myText". E.g.:
<div id="myText">This is what's shown before Javascript runs.</div>
Then in your Javascript code you can do:
document.getElementById("myText").innerHTML='<img src=test.gif></img><p> Testing 123 </p>';
That will fill your element with the above code with the obvious consequences (adding image and text) if that's what you want.
Update: If you're calling your Javascript function with the onload event, be sure to put onload="myFunction()" assignment into the body tag, since it doesn't work in div, p and so on. Alternatively, you can use onClick instead of onload which will work with div, p and other elements.
The code below should work. The problem was that the <p> element does not fire the onload event, but the body does.
<body onload="HTMLThing()">
<p id="myText">Soon.</p>
<script type="text/javascript">
var testString = "<img src=test.gif></img><p> Testing 123 </p>";
function HTMLThing(){
document.getElementById("myText").innerHTML = testString;
}
</script>
</body>
There are several ways to do the onload event, another method:
<body>
<p id="myText">Soon.</p>
<script type="text/javascript">
var testString = "<img src=test.gif></img><p> Testing 123 </p>";
function HTMLThing(){
document.getElementById("myText").innerHTML = testString;
}
window.onload = function(){
HTMLThing();
}
</script>
</body>

Calling JavaScript function into a P tag

I would like to call the following javaScript function so it gets outputted to a HTML P tag, but am not sure how to do this without explicitly calling the function in the HTML file.
I do not want to do this...
<p class="showcode">
<script type="text/javascript">
wise_words();
</script>
</p>
I would like to keep the javaScript code all in one js file.
I have tried it this way but this does not seem to work...
document.getElementById("showcode").innerHTML = wise_words();
I would really appreciate any help as to what I am doing wrong.
Here is my code... http://codepen.io/anon/pen/qfLdE I would like to have the generated text get outputted inside the grey box.
You should call the function in an onload handler, so that it is executed after the DOM has been constructed:
window.onload = function() {
document.getElementById("showcode").innerHTML = wise_words();
}
Another problem is that your wise_words() function is using document.write (please don't use document.write) instead of returning a value. You need to return a value:
var retText = wiseText[nextVal][0];
nextVal += 1;
writeCookie("wisewords", nextVal.toString(), 33);
return retText;
Try following using Jquery:
$(".showcode").html(wise_words());
NOTE: Assuming your function returns the HTML/text.
<p class="showcode">
<script type="text/javascript">
document.write(wise_words());
</script>
</p>
or:
<body onload="document.getElementById('showcode').innerHTML = wise_words()">
<p id="showcode">
</p>
</body>
(note id instead of class).

Override existing HTML Element attribute and property with Javascript

I was wondering if its possible to override existing HTML Element attribute and property accessors (getters and setters) with Javascript so that when html is rendered by browser all the assignments to certain attributes in the html code are preprocessed with custom functionality.
Here is an example :
<html>
<head>
<script>
// JS code would go here which would override default behavior
// for example if I wanted to reformat id="name" so its actually
// registered as id="pre_name" once browser renders the html
</script>
</head>
<body>
<!-- here we are assigning the 'name' to id , but behind the scene we really want it to be 'pre_name' -->
<div id="name"></div>
<script>
// when we try to access the id it would actually match the overwritten one
console.log(document.body.children[0].id) // would output pre_name
</script>
</body>
</html>
Is something like that possible and how?
I know that I can traverse the dom after it's rendered and change all of the ids, but I am wondering if its possible to intercept the assignment of properties and attributes and do it at that level before browser even renders the html.
Example I presented is just made up one to present the problem and make is simple to understand.
Thanks
Unfortunately this is not possible, you can only modify the name element after it is loaded.
So it would be something like this:
<body>
<!-- here we are assigning the 'name' to id , but behind the scene we really want it to be 'pre_name' -->
<div id="name"></div>
<script>
// right after
document.getElementById('name').id = 'pre_name';
</script>
<script>
// when we try to access the id it would actually match the overwritten one
console.log(document.body.children[0].id) // would output pre_name
</script>
</body>
or even
<body>
<!-- here we are assigning the 'name' to id , but behind the scene we really want it to be 'pre_name' -->
<div id="name"></div>
<script>
// or here
document.getElementById('name').id = 'pre_name';
// when we try to access the id it would actually match the overwritten one
console.log(document.body.children[0].id) // would output pre_name
</script>
</body>
You can use html data-* attributes for second value like;
<div id="name" data-second="pre_name"></div>
And then you can use,
var div = document.getElementById('name');
div.getAttribute("data-second");

html assigning value to input text using javascript does not work

I am new to programming and I have a small problem
I have a form named "fr" with an input text box named "in" and a variable "n" with the value of "my text"
this is my code what I have:
<html>
<head>
<script LANGUAGE="JavaScript">
var n = "my text";
document.fr.in.value = n;
</script>
</head>
<body>
<form name="fr">
<input name="in" size="3">
</form>
</body>
</html>
but somehow input "in" does not show the text "my text"
I have been browsing the internet but I couldn't find any solution which works..
everything what I try does not work.
I think I am doing something very simple wrong.
please help me.
document.fr does not exist yet at time of invocation; hence, everything following it doesn't exist either, so it throws a TypeError
TypeError: Cannot read property 'in' of undefined
To fix this, move your code to be invoked after the nodes exist, using your favourite method
window.addEventListener('load', function () {
var n = "my text";
document.fr.in.value = n;
});
I'll further note that;
The preferred way to look up an Element is to give it an id attribute and use document.getElementById. An id must be unique.
Using the language attribute of <script> is depreciated, if you want to specify the language, use the type attribute type="text/javascript" or type="application/javascript"
Opening the Console when a script is not working as expected will often show you the cause immediately. This is usually done with F12.
You should init the script after the form is defined, as explained by Paul S. in his answer. So you may do,
<html>
<head>
</head>
<body>
<form name="fr">
<input name="in" size="3">
</form>
<script type="text/javascript">
var n = "my text";
document.forms.fr.in.value = n;
</script>
</body>
</html>
This would run the script after the form is defined. Or put this code in some function, and instantiate the function after the form is defined(i.e. loaded).
As Paul pointed out you should only try to get a hold of page elements when you are certain that the element you are interested has already been loaded. So in this case you can set the value of the input field by running your code when the page has fully loaded and by getting a reference to the input like this:
window.addEventListener("load", function () {
var n = "my text";
var myInput = document.getElementsByName("in");
myInput[0].value = n;
});
Note, because getElementsByName() returns an array, you will have to use [0], to get the first element.

Categories

Resources