Events and handlers JavaScript - javascript

I am writing a code in which I want to display a word and sentence to my webpage when clicked(button). So far I have one text being displayed onto the page.I want to display the sentence after the text.The sentence is not displaying... anyone know why?
function handleButtonClick(){
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
var textInput = document.getElementById("word");
var termName = textInput.value;
var dt = document.createElement("dt");
dt.innerHTML = termName;
var dl = document.getElementById("p");
dl.appendChild(dt);
var textInput = document.getElementById("sentence");
var termDefine = textInput.value;
var dd = document.createElement("dd");
dd.innerHTML = termDefine;
var dl = document.getElementById("define");
dl.appendChild(d);
}
window.onload = handleButtonClick;

button.onclick = handleButtonClick;
supposed to be
button.addEventListener('click', handleButtonClick);
The second point is that the click event handler should be bound outside the function scope. Otherwise a new event will be bound every single time the function handleButtonClick fires.
var button = document.getElementById("addButton");
button.addEventListener('click', handleButtonClick);
function handleButtonClick() {
// Your other code here
// that excludes the click handler
}
And developer tools is your friend. Always use it to check for any errors.

In addition to what #sushanth already mentioned there is a typo in your code:
Instead of
dl.appendChild(d);
It should be
dl.appendChild(dd);

Related

jQuery function .one is not woking

Every time I click the add icon, the addFunction() in javascript file invokes. And each time the function invokes, it attaches a click function to the unordered list.
To avoid attachment of multiple click functions I used .one instead of .on but this approach is not working.
HTML:
ul#classesAndSubjectsList
each value, index in user.classesAndSubjects
li !{value}
a.ml-4#classesAndSubjects(href='javascript:;')
i.fa.fa-plus(aria-hidden="true")
Javascript:
addFunction = function() {
const txt = prompt(promptMsg1, promptMsg2);
if (!(txt == null || txt == "")) {
const i = document.createElement("i");
i.classList.add("fa");
i.classList.add("fa-times");
i.classList.add('red-cross');
const a = document.createElement("a");
a.classList.add("ml-4");
a.append(i);
const t = document.createTextNode(txt)
const newItem = document.createElement("li");
newItem.append(t);
newItem.append(a);
var final = $("ul#classesAndSubjectsList");
// No idea why .one is not working
final.one('click', 'li a', function () {
//other code
});
$(final).append(newItem);
}
}
$("a#classesAndSubjects").click(function(){
addFunction();
});

Including strings as parameters for a function chosen for .setAttribute to a button in javascript

I want to be able to pass along a string as a value for a button's onclick function using setAttribute. I am getting the error that "add is not defined" when I click on the button and I am not sure what I am doing wrong.
var AddButton = document.createElement("button");
var AddString = "add";
var SectorString = "1_1";
AddButton.setAttribute("onclick",'AddOrDeleteDiv(AddString,SectorString)');
function AddOrDeleteDiv(AddString, SectorString) {
//code
}
Do not use content attribute event handlers! Use event listeners instead:
var addButton = document.createElement("button");
var addString = "add";
var sectorString = "1_1";
addButton.addEventListener('click', function() {
addOrDeleteDiv(addString, sectorString);
});
function addOrDeleteDiv(addString, sectorString) {
//code
}
Well js is known for not having nice methods for string joining and please try to use function parameter names not same as global variable names, it's not a nice thing to do.
var AddButton = document.createElement("button");
var AddString = "add";
var SectorString = "1_1";
AddButton.setAttribute("onclick",'AddOrDeleteDiv(' + JSON.stringify(AddString) + ',' + JSON.stringify(SectorString) + ')');
function AddOrDeleteDiv(addStr, secStr) {
//code
}
or as #Thomas said you could use acutual javascript event handler like , not modifying attributes to assign event handler
AddButton.onclick = function(){AddOrDeleteDiv(AddString,SectorString);}

How do I change an onclick function to have multiple functions?

I'm trying to change a button's onclick function to remove one function and add two functions. This is my current code
var random;
function number(){
var random =Math.floor(Math.random()*Math.floor(Math.random()*20))
}
function show(){
var display = document.getElementById('number').innerHTML= random;
}
function start(){
var random =Math.floor(Math.random()*Math.floor(Math.random()*20))
var button = document.getElementById('button').innerHTML="I give up!!";
var change = document.getElementById("button").onclick = show; number;
}
Add 2 event listeners to your button
function start(){
var random = Math.floor(Math.random()*Math.floor(Math.random()*20)),
button = document.getElementById('button').innerHTML="I give up!!";
changeButton = document.getElementById("button");
changeButton.addEventListener('click', show);
changeButton.addEventListener('click', number);
}
You need to assign onclick an anonymous function and include both functions in it:
document.getElementById("button").onclick = function() {
show();
number();
};

addEventListener won't work because of null

All I'm trying to do is have the user click the button, and when that event occurs I want an image to display within a div. I inspected the element, and it says that tableButton is undefined, but I defined it right before the addEventListener. What am I doing wrong? Sorry, I'm new to javascript.
function openTable() {
var code = "<img src='PeriodicTableOfElements.png'>";
var periodic = document.getElementById("Periodic");
periodic.innerHTML = code;
}
var tableButton = document.getElementById("openTable");
tableButton.addEventListener("click", openTable, false);
Have you made sure to wrap it in window.onload, elements can't exist if the window hasn't loaded.
window.onload = function(){
function openTable() {
var code = "<img src='PeriodicTableOfElements.png'>";
var periodic = document.getElementById("Periodic");
periodic.innerHTML = code;
}
var tableButton = document.getElementById("openTable");
tableButton.addEventListener("click", openTable, false);
}

Creating two elements using js and then having access to them later in another function

I am building some js functionality where I will be creating 2 elements on a page
var createBtn = function(
var btn = document.createElement('button')
...
)
var createIframe = function(
var iframe = document.createElement('iframe')
...
)
Pretty basic stuff, but later on I want to add an event listener to the button that will apply a style attribute to the iframe.
Something like:
var displayIframe = function(
Iframe.style['display'] = 'block'
)
button.addEventListener('click', displayIframe)
My question is how can I access the elements after I have created them without going through the annoyance of attaching classes to them and accessing them all over again that way. Is there someway of getting access to them in the create functions from the beginning.
Your codes is almost correct, but some changes is needed
var btn, iframe;
var createBtn = function () {
btn = document.createElement('button');
...
}
var createIframe = function () {
iframe = document.createElement('iframe');
...
}
Callback function
var displayIframe = function(){
iframe.style['display'] = 'block'
}
Attach click listener
btn.addEventListener('click', displayIframe);
Your mistakes:
you should declare btn and iframe as global variables to be accessible to other functions
function starts with { and ends with } not (, )
so far your codes is correct, without any error, but you won't see anything on the page because you have not attached your newly created elements to the body, For accomplish this try this function
function attachToBody(){
document.body.appendChild(btn);
document.body.appendChild(iframe);
}
In your example, I dont know why you use functions to create element, but you must have your point. Try this and let me know does this work for you.
//this is equivalent to: var btn = document.createElement('button');
var btn = (function(){
var btn = document.createElement('button');
return btn;
})();
var iframe = (function{
var iframe = document.createElement('iframe');
return iframe;
})();
document.getElementById("parentId").appendChild(btn);
document.getElementById("parentId").appendChild(iframe);
btn.addEventListener('click', function(){
iframe.style.display = "none";
});
var createBtn = function() {
var btn = document.createElement('button')
btn.setAttribute("id", "myButton");
return btn;
}
var createIframe = function() {
var iframe = document.createElement('iframe')
iframe.setAttribute("id", "myFrame");
return iframe;
}
document.body.appendChild(createBtn()); // Append button to body.
document.body.appendChild(createIframe()); // Append iFrame to body.
// Get Elements by Id.
var myButton = document.getElementById("myButton");
var myFrame = document.getElementById("myFrame");
// Add event listener.
myButton.addEventListener("click", function() {
myFrame.style.display = "none", false);
}

Categories