Setting onclick function dynamically in Javascript not working - javascript

hello =) I am trying to create a heading tag with some text in it.
var d = document.createElement("h5");
d.innerHTML = "Dungeon";
and then assigning an onclick listener.
d.onclick = function(){myFunction()};
which doesn't seem to be working. I've also tried
d.onmousedown = function(){myFunction();};
and
d.onclick = "myFunction()";
and
d.addEventListener("mousedown", function(){myFunction});
and none of them seem to be working. I have thrown in a couple tracers around it, everything runs through fine without syntax errors but the actual element when appended to the document doesn't have the function tied to it at all. Would anyone happen to know why? Thanks in advance =)
Edit:
Here is a more detailed block of my code. Would this make any difference?
var x = document.createElement("ul");
var y = document.createElement("li");
x.appendChild(y);
var d = document.createElement("h5");
d.innerHTML = "Dungeon";
y.appendChild(d);
console.log(0);
d.onclick = function() { alert('test'); }
console.log(1);

elem.addEventListener("click", function, false);

Related

how to add events as attribute to an element

I have this code:
var elmnt = document.createElement("div");
elmnt.onclick = function () {
alert("hello");
}
at this time, elmnt.outerHTML is <div></div>.
But this is what I want to get:
<div onclick="alert('hello')"></div>
I really don't know what I'm looking for,
would you help me?
This worked for me:
var elmnt = document.createElement("div");
// var elmnt_text = document.createTextNode('click to see alert');
// elmnt.appendChild(elmnt_text);
elmnt.addEventListener('click', function(){
alert('hello')
})
document.body.appendChild(elmnt);
By commenting the two lines of code, you will see the div with its handler when you inspect element as in
<div onclick="alert('hello')"></div>
However, I wanted to be sure that it works so I dynamically created a text node for the div for testing purpose, and the click event fires as expected.
Hope this helps.

Dynamically increasing font size

I would like to increase the font size of the paragraph as well as the font size of the number in the button.
I copied and pasted my sizer function from StackOverflow (a few alterations) and thought it would work and still can't get it to work. Can someone help?
Since I've spent so much time on just the first part, as a beginner programmer, I'm wondering what I am missing. Does anyone have any ideas from my code or their experience as to what I might be missing?
Thanks as always.
<html>
<button onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
sizer = function changeFontSize() {
div = document.getElementById("test");
currentFont = div.style.fontSize.replace("pt", "");
div.style.fontSize = parseInt(currentFont) + parseInt(clicks) + "pt";
}
</script>
</html>
Some things here:
I woudn't append two functions to your onclick here. Just append one and call your second function from the first one that gets fired via onclick. That looks a lot more tidy
Don't forget to put var before every variable, without it's not valid JavaScript
I didn't quite understand what you tried with your currentFont variable, so I removed it. It's not necessary and causes the script to not working correctly
<html>
<button onclick='incrementer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
var clicks = 0;
var incrementer = function() {
clicks += 1;
var click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
sizer();
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
div.style.fontSize = parseInt(clicks) + "pt";
}
</script>
</html>
Here's a from-scratch version that does what you're asking for. I'll point out a few things that I did to help you out.
https://codepen.io/anon/pen/VBPpZL?editors=1010
<html>
<body>
<button id="count">0</button>
<p id="test">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</p>
</body>
</html>
JS:
window.addEventListener('load', () => {
const button = document.querySelector('#count');
const paragraph = document.querySelector('#test');
const startingFontSize = window.getComputedStyle(document.body, null)
.getPropertyValue('font-size')
.slice(0, 2) * 1;
let clicks = 0;
button.addEventListener('click', () => {
clicks++;
// this is a template literal
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const fontSize = `${startingFontSize + clicks}px`;
button.innerHTML = clicks;
button.style.fontSize = fontSize;
paragraph.style.fontSize = fontSize;
});
});
The code runs when the page is loaded, so we attach an event listener on the window object listening for the load event.
We then store references to the button and the paragraph elements. These are const variables because their values won't change. This also limits their scope to the containing function.
We get the initial font size for the body element, because in this example we aren't explicitly setting a base font in css so we're just using the one for the document. getComputedStyle is a somewhat expensive operation, and in this case we only need to get it in the beginning because it won't change, so we also store it as a const. The value is returned as a string like "16px" but we need the number, hence the slice and multiplying by one to cast the string into a number. parseInt would also do the same thing.
Notice that clicks is defined with let. This means that the variable can be changed. var still works of course, but in modern practices its best to use const and let when declaring variables. This is partly because it forces you to think about what kind of data you're working with.
We add an event listener to the button element and listen for the click event. First, we increment the clicks variable. Then we declare fontSize using a template literal which adds our new clicks count to the startingFontSize and "px" to get a string.
Finally, the innerHTML value of the button element is updated. Then we update the fontStyle property for both elements.
The issue here is that there is no initial value for the fontSize of your <p> tag so div.style.fontSize returns an empty string.
You can use window.getComputedStyle instead of div.style.fontSize and you will get the current fontSize.
There is already a post explaining this method
https://stackoverflow.com/a/15195345/7190518
You don't have an initial font-size style on your <p> tag, so it div.style.fontSize is always empty. Also, best practice is to always use var when introducing new variables in javascript.
One good trick to help debugging things like these is to use console.log() at various points, and see whats coming out in your browser console. I used console.log(div.style.fontSize) and the answer became clear.
Working below after adding <p style='font-size:12px'>a</p>:
<html>
<button style='font-size:12px;' onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test' style='font-size:12px;'>a</p>
<script>
var clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
var btn = document.getElementById("count");
var newSize = parseInt(div.style.fontSize.replace("pt", "")) + parseInt(clicks);
div.style.fontSize = newSize + "pt";
btn.style.fontSize = newSize + "pt";
}
</script>
</html>
I don't understand the logic of this solution, but you can simplify it avoiding to use a lot of var (anyway always prefer let or const if you don't need to change), using a single function and writing less code.
function increment(e){
const ctrl = document.getElementById('test');
let current = parseInt(e.dataset.size);
current += 1;
e.innerHTML = current;
e.dataset.size = current;
ctrl.style.fontSize = current + 'pt';
}
<button onclick="increment(this);" data-size="20">20</button>
<p id='test' style="font-size:20pt;">A</p>

How to dynamically create list of <a> tags using js

I am creating html page which needs to create a list of links dynamically on a click of button. I know how to create this list when number of links to be created is known before like this:
//For 4 tags:
var mydiv = document.getElementById("myDiv");
var aTag = document.createElement('a');
aTag.innerHTML = "link1 text";
aTag.setAttribute('onclick',"func()");
mydiv.appendChild(aTag);
var bTag = document.createElement('b');
bTag.innerHTML = "link2 text";
bTag.setAttribute('onclick',"func()");
mydiv.appendChild(bTag);
var cTag = document.createElement('c');
cTag.innerHTML = "link3 text";
cTag.setAttribute('onclick',"func()");
mydiv.appendChild(cTag);
var dTag = document.createElement('d');
dTag.setAttribute('onclick',"func()");
dTag.innerHTML = "link4 text";
mydiv.appendChild(dTag);
But the problem is that the count will be known at run time and also on function call i need to identify the id of link that invoked function.. Can anybody help?
I don't know weather you receive or not the HTML to be shown in the anchor, but anyway, this should do the work:
function createAnchor(id, somethingElse) {
var anchor = document.createElement('a');
anchor.innerHTML = "link" + id + " text";
anchor.setAttribute("onclick", "func()");
return anchor;
}
Then you call the function like this:
function main(num_anchors) {
var mydiv = document.getElementById("myDiv");
for (var i = 0; i < num_anchors; i += 1) {
mydiv.appendChild(createAnchor(i));
}
}
Of course this code can be improved, but this is just for show how can this be possible.
Yes it is possible to do this at runtime .
JQuery provides very useful dom manipulation . So you can traverse the dom , filter what you need ..
you can find a lot of useful functions here .
http://api.jquery.com/category/traversing/
It would look something like this.
$( document ).ready(function() {
$( "a" ).each(function( index ) {
// enter code here..
}
});
document.ready gets invoked once the DOM has loaded.

Cannot remove a div in Javascript

I'm trying to remove a div in Javascript but 'its not working. I get no error in my console yet the function does get called.
I don't understand what I have done wrong, so I'm hoping someone can explain. This is how it works:
function menu_load(type){
document.getElementById(type).onclick = function(){ menu_unload(type); }
var width = 100;
var height = 100;
var d = document.createElement('div');
d.id = 'menu';
d.className = 'menu';
d.style.width = width + 'px';
d.style.height = height + 'px';
document.getElementById('G').appendChild(d);
}
function menu_unload(type){
alert('test'); //this displays
var div = document.getElementById("menu");
div.parentNode.removeChild(div); // doesn't remove the div
document.getElementById(type).onclick = menu_load(type);
}
window.onload = function(){
menu_load('test');
}
Is there any mistake here that I have missed? I just can't work out the problem.
Your code works for me if I correct the following line:
document.getElementById(type).onclick = menu_load(type);
Which incorrectly calls menu_load() and tries to assign the result to .onclick. It should be like you did in the other function
document.getElementById(type).onclick = function() { menu_load(type); };
Demo: http://jsfiddle.net/MCZza/
To be honest I don't know why this fixes it, since your code wasn't actually a syntax error, but because it called menu_load() it recreated the div just removed. and the .removeChild() line should happen first, but anyway...

FCKEditor: Access content area

I'm having problems doing this. I can't access the content area object. I need it to attach a click listener.
var oFCKeditor = new FCKeditor( editorName ) ;
oFCKeditor.BasePath = o.editorPath;
if (o.configPath) {
oFCKeditor.Config["CustomConfigurationsPath"] = o.configPath +"?" + ( new Date() * 1 ) ;
}
oFCKeditor.Width = '100%';
oFCKeditor.Height = '100%';
oFCKeditor.ReplaceTextarea();
oFCKeditor.setEnabled(true);
alert(oFCKeditor.EditorDocument);
alert(oFCKeditor.EditorWindow);
alert(FCK);
I also tried accessing there objects from different parts inside FCKEditor's code, but no luck.
What am I doing wrong? What is the usual way to do this?
Thanks
Edit: when I do this:
var oEditor = FCKeditorAPI.GetInstance(editorName) ;
alert(oEditor.EditorDocument);
after creating the editor it works, but only when I'm stepping through it with a debugger, otherwise it's undefined. So it's probably a timing issue. But where am I supposed to get that then?
http://docs.cksource.com/FCKeditor_2.x/Developers_Guide/JavaScript_API#Events
<script type="text/javascript">
var object;
function FCKeditor_OnComplete(editorInstance)
{
object = editorInstance;
}
function Display()
{
alert( object.GetHTML());
}
</script>

Categories

Resources