Accessing buttons created in another file - javascript - javascript

I am trying to create a button in a function declared in an external javascript file. With the html file (in some sense the "main" file), I am trying to access this button and assign click listeners. I am not able to do so. Please see below for the code I have so far.
testDialogJS.js:
/**
* The JS here will be referenced from another file.
*/
function creator() {
console.log("creator.");
var btn = document.createElement("BUTTON");
var text = document.createTextNode("Click me!");
btn.setAttribute("id", "Button");
btn.appendChild(text);
}
testDialog.html:
<html>
<head>
<style>
.hlight{background-color:#ffcc00; }
textarea {
width:100%;
height:100%;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css"/>
<!-- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.js"></script> -->
<script type="text/javascript" src="testDialogJS.js"></script>
<script type="text/javascript">
window.onload=function() {
console.log("Window has been loaded.");
creator(); //this function is elsewhere.
var btn = document.getElementById("Button");
if(btn == null) {
console.log("Button is null.");
} else {
console.log("Button is not null.");
btn.onclick=function() {
console.log("Hello.");
}
}
}
</script>
</head>
<body>
</body>
</html>

You have not appended your button to the document. So this returns null when you try to select the button using document.getElementById("Button")
Add the following statement in creator() like this
function creator() {
console.log("creator.");
var btn = document.createElement("BUTTON");
var text = document.createTextNode("Click me!");
btn.setAttribute("id", "mybtn");
btn.appendChild(text);
document.body.appendChild(btn);
}
Demo

Related

HTML DOM createElement() [duplicate]

I'm trying to use javascript to create a button that has a onclick event that calls a function defined in the head that takes in as parameter a dom object relative to the button. how do i do this?
ex:
<html>
<head> <script>function blah(obj){alert(obj.value)}</script></head>
<body>
<button onclick="blah(this.parentNode.value);"></button>
</body>
</html>
javascript:
var newButton = document.createElement("button");
???
in the end i want the new button to be the same as the existing one.
function createButton(context, func) {
var button = document.createElement("input");
button.type = "button";
button.value = "im a button";
button.onclick = func;
context.appendChild(button);
}
window.onload = function() {
createButton(document.body, function() {
highlight(this.parentNode.childNodes[1]);
// Example of different context, copied function etc
// createButton(this.parentNode, this.onclick);
});
};
Is that what you want?
You can also use the built-in setAttrbute javascript function.
var newButton = document.createElement("button")
newButton.setAttribute("onclick", "blah(this.parentNode.value)")
Hope it will help

Changing An Elements Content

I would like to change the content of a element with a button click and then have it return back to its original message. How Would i do this preferable with toggle class if possible.
<doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Day Practice</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"> </script>
</head>
<body>
<h1> HotDogs</h1>
<input type=button id=button value=button>
<script>
$("#button").click(function(){
$("h1").html("Change to this");
});
</script>
This changes the header with a button, but I don't know how to revert it when I click on the button again. Maybe Toggle Class, I don't know.
this should solve:
$( "#button" ).toggle(function() {
$("h1").html("Change here");
}, function() {
$("h1").html("Revert back here");
});
Set a flag to toggle and check, and store the old text whenever you change it. An example:
var flag = false;
var old_text = "";
$("#button").click(function () {
if (flag) {
$("h1").html(old_text);
} else {
old_text = $("h1").html();
$("h1").html("Change to this");
}
flag = !flag;
});
You can try this:
var alternate_text = "Change to this";
$("#button").click(function(){
var temp = $("h1").html()
$("h1").html(alternate_text);
alternate_text = temp; // Switch the two instances of text.
});
Since you prefered to do this with toggleClass(), here you go:
$(document).ready(function(){
var oldContent;
$("#button").click(function(){
if($(".newCont")[0]){
$("h1").html(oldContent);
} else {
oldContent = $("h1").html();
$("h1").html("New text here");
}
$("h1").toggleClass("newCont");
});
});

Incrementing a counter when a button is clicked (JavaScript, HTML)

I want to display a button for an HTML document, and each time this button is clicked it increments.
After incrementation I want that number(which is the counter to be saved) for when the file is accessed again the counter shows for the users.
What I read is that there is a function called addBtn, which on click increments how is it possible to save the incremented value
addBtn.on("click", function() {
counter.html(++value);
return;
});
That would be something like this. Just replace the "your_textfield" with your selector.
var counter = 1;
function increase(){
var textBox = document.getElementById("your_textfield");
textBox.value = counter;
counter ++;
}
addBtn.on("click", function() {
var counter=$(this).html();
counter+=1;
$(this).html(counter);
return;
});
If you want to do it with a file you need a php to do it for you
but this one is a simple one using localstorage of web browers
you can check the console log of your browser
where in its shows a object storage
<html>
<head>
<style>
.overlay {
background-color: rgba(0,0,0,0.5);
width: 100%;
height: 100%
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<p class="display"></p>
<input type="button" class="add" value="click me">
<script type="text/javascript">
$(document).on('ready', function(){
var count = 0;
var storage = window.localStorage;
var disp = $('p.display');
if (storage.getItem('count')) {
count = parseInt(storage.getItem('count'));
disp.html(count);
}
$('.add').on('click', function(){
if (storage.getItem('count') != null) {
count = parseInt(storage.getItem('count'));
}
count++;
storage.setItem('count', count);
disp.html(count);
console.log(storage);
});
});
</script>
</body>
</html>

Error in appendchild

I have the following very simple code:
<html>
<head>
<script type="text/javascript" >
function showAlert(){
alert("I am clicked");
}
function one(){
var a1 = [1,2,3];
for (var i=0;i<a1.length;i++) {
var p = document.createElement('p');
p.innerHTML = a1[i];
p.onclick = showAlert;
document.body.appendChild(p);
}
console.log("I am called");
}
one();
</script>
</head>
</html>
I am getting the following error:Uncaught TypeError: Cannot read property 'appendChild' of null. Can anybody tell me, where am I going wrong? I am testing in Chrome.
document.body.appendChild is run before the body is defined, hence document.body is still null.
Either move this script down under the <body></body> or delay it's execution with:
window.addEventListener("load", function () { /* we're ready */ });
document.body.appendChild(p)
In this line. Some days ago I had the same problem.
This happens if you put your script before of the tag body.
<html>
<head>
<script type="text/javascript" >
function showAlert(){
alert("I am clicked");
}
function one(){
var a1 = [1,2,3];
for (var i=0;i<a1.length;i++) {
var p = document.createElement('p');
p.innerHTML = a1[i];
p.onclick = showAlert;
document.body.appendChild(p);
}
console.log("I am called");
}
one();
</script>
</head>
</html>
Will not work.
If you put your function call after the tag it works.
<html>
<head>
<script>
function showAlert(){
alert("I am clicked");
}
function one(){
var a1 = [1,2,3];
for (var i=0;i<a1.length;i++) {
var p = document.createElement('p');
p.innerHTML = a1[i];
p.onclick = showAlert;
document.body.appendChild(p);
}
console.log("I am called");
}
</script>
</head>
<body>
<body>
<script type="text/javascript" >
one();
</script>
</html>
In your context, "body" yet didn't be initialized, so it is null
It looks like you are missing the body tag from your HTML. So document.body is null

Click handler losing reference to "this" object that created it

I made JS script:
var zzz;
zzz = {
fff: function (Id) {
alert("You did it! Id="+Id);
},
main: function (Id) {
var button, elements;
button = document.createElement("input");
button.type = "submit";
button.onclick = function () {
zzz.fff(Id);
};
elements = document.getElementById(Id);
elements.appendChild(button);
}
};
and HTML, where I tested it:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8">
<title>My Web Page!</title>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<div id="div001"></div>
<div id="div002"></div>
<script type="text/javascript">
object1 = zzz;
object1.main("div001");
object2 = zzz;
object2.main("div002");
</script>
</body>
</html>
Why it works only if I write button.onclick = function () { zzz.fff(Id); }; and with this.fff(Id) it doesn't work?
When you bind an event handler (such as onclick), inside the handler this becomes the element that triggered the event (except if you used an inline onclick="" attribute, which should be avoided).
Instead of using zzz, you could also copy this to another variable that would be available inside the handler via closure:
var that = this;
button.onclick = function () {
that.fff(Id);
};
Or you could use Function.prototype.bind:
var clickHandler = button.onclick = function () {
this.fff(Id);
};
button.onclick = clickHandler.bind(this);

Categories