I am trying to create a library code that can be used across all my html pages.
I am very new to JS and this is the first code that I am trying to write like a library function.
I have a text field and a button next to it, on click of the button this adds a another text field below and a button next to it, this also removes the button in previous line.
I managed to do a button in the same row and adding text field in next lines, but the button click for newly added methods are not working with pure JS so I tried to use jquery "on" click event. For some reason its not getting triggered in my case.
Not sure what I am missing.
Code in external file
var addAnother = {
addAnotherField: function (eventTrigger, fieldContainer, arrayField) {
console.log("called");
var eventTrigger = eventTrigger;
console.log("ready called", eventTrigger);
$(document).on('click', eventTrigger, function (e) {
console.log("click called");
var buttonText = this.value;
var div = document.getElementById(fieldContainer);
var element = document.getElementById(eventTrigger);
element.parentNode.removeChild(element);
var input = document.createElement("input");
input.type = "text";
input.name = arrayField;
div.appendChild(document.createElement("br"));
div.appendChild(input);
var button = document.createElement("input");
button.type = "button";
button.id = eventTrigger;
button.value = buttonText;
div.appendChild(button);
});
}
}
code in HTML
$(document).ready(function () {
addAnother.addAnotherField("addAnother", "addAnotherContainer", "fieldArray[]");
});
Working JS code:
http://jsfiddle.net/balasivagnanam/ekoob8f0/
next button non working code JS
http://jsfiddle.net/balasivagnanam/ukseeuak/
with Jquery:
http://jsfiddle.net/balasivagnanam/6ea2dk6m/
Is this what you want:
/** this part will be located in another file added as a js library */
function addAnother(elem) {
var text = $("#addAnotherField").clone();
$("<br/>").insertBefore($("#addAnother"));
text.insertBefore($("#addAnother"));
}
/* this part will be coded below the above code file in the html file*/
$(document).ready(function () {
$('#addAnother').click(function () {
addAnother(this);
});
});
Here is the JSFiddle demo
Related
Problem
Adding an event handler for click events with dynamically added buttons does not result in anything when clicked. I'm trying to build a build a chrome extension that dynamically adds a button.
Code
In content script (js)
// 1. Create the button
var button = document.createElement("button");
button.innerHTML = "Do Something";
// 2. Append somewhere in the document body
var body = document.getElementsByTagName("body")[0];
body.appendChild(button);
// 3. Add event handler
button.addEventListener ("click", function() {
alert("did something");
});
While the button does get rendered, clicking the button does nothing.
Notes
Event handlers for checkboxes work, though! Uses href = "javascript: function()"
var check = document.createElement("input");
check.id = "checkbox1";
check.type = "checkbox";
//if check is checked, then call removeSticky()
check.href="javascript:removeSticky()"
check.addEventListener('change', () => {
if (check.checked) {
removeSticky();
} else {
// nothing
}
});
document.getElementById("sticky").append(check);
//hidesthe sticky note
function removeSticky() {
window.alert("removeSticky() is working.");
// Removes an element from the document.
var element = document.getElementById("sticky");
element.style.display = "none";
}
However, doing the same with the BUTTON causes removeSticky() to be called whenever the webpage is fully loaded, when the user hasn't clicked anything yet.
I want to add data-id from a button in favorite list.
I tried few solution but the click action is never detected in console .
html code is
<button class="icon-plus-circle i-circled i-small addToCart" date-id="myId" data-name="myName"></button>
js code is
button.addEventListener('click', function (){
var id = $(this).attr('data-id');
var name = $(this).attr('data-name');
console.log(id);
let Fav = {
id : id ,
name : name
};
let liste_json = JSON.stringify(Fav);
localStorage.setItem('listeFavoris', JSON.stringify(liste_json));
} )
You need to select the button
const button = document.querySelector('button');
const button = document.querySelector('button');
button.addEventListener('click', function() {
console.log('click detected');
});
<button>Click Me</button>
PS - You have added click listener using javascript and have jQuery code inside. Don't mix up two, stick with one.
I am trying to make a simple Shopping List App in which user can Add, Delete and mark the task done when completed. So far, I am able to add the task but facing problem in executing the done and delete functions. I am getting an error because when I execute it, the done and delete buttons are not there but what should I do to fix it?
var inp = document.getElementById("form");
var button = document.getElementById("click");
//Create List Function with Done and Delete Buttons
function addVal() {
var ul = document.getElementById("list");
var li = document.createElement("li");
var span = document.createElement("span");
var done = document.createElement("button");
var del = document.createElement("button");
li.appendChild(document.createTextNode(""));
span.appendChild(document.createTextNode(inp.value));
done.appendChild(document.createTextNode("Done"));
del.appendChild(document.createTextNode("Delete"));
li.appendChild(span);
li.appendChild(done);
li.appendChild(del);
done.setAttribute("class", "doneBut");
del.setAttribute("class", "delBut");
ul.appendChild(li);
inp.value = "";
}
//Get Input Length
function checkLength() {
return inp.value.length;
}
//Run function on Button Click
function onButtonClick() {
if (checkLength() > 0) {
addVal();
}
}
//Run function on Enter Keypress
function onEnter(event) {
if (checkLength() > 0 && event.which === 13) {
addVal();
}
}
//Trigger Events
button.addEventListener("click", onButtonClick);
inp.addEventListener("keypress", onEnter);
//Done and Delete Button Functions
var doneButton = document.getElementsByClassName("doneBut");
var deleteButton = document.getElementsByClassName("delBut");
function doneTask() {
doneButton.parentNode.classList.add("done");
}
function delTask() {
deleteButton.parentNode.classList.add("delete");
}
doneButton.addEventListener("click", doneTask);
deleteButton.addEventListener("click", delTask);
<input type="text" placeholder="Enter Your Task..." id="form" />
<button id="click">Add Task</button>
<h2>List:</h2>
<ul id="list"></ul>
Please Help.
Your problem is that the code tries to add events before the buttons exist. The buttons don’t exist until the addVal function gets called. Since addVal is not being called before the you try to add your event handlers, the getElementById returns null, and you attempt to add an event listener to null.
Additionally it looks like you’re planning to add multiple done and delete buttons. That wouldn’t normally be a problem, except you’re referencing them by ID, and IDs MUST be unique. You’ll need to switch this to a class or an attribute, since you’ll need one per item in the shopping cart.
You’ll probably want to look into event delegation, so that you can add your events once to the page before any buttons exist. https://javascript.info/event-delegation
It's most likely because your script is running before your code is running. Add the <script> tags just before the closing </body> tag to fix it:
<script>/* Your code here */</script>
</body>
You need to place this in a window.onload function, or run it in a function inside of the body tag's onload. Those elements don't exist yet when the script is run:
window.onload = function() {
var inp = document.getElementById("form");
var button = document.getElementById("click");
button.addEventListener("click", onButtonClick);
inp.addEventListener("keypress", onEnter);
}
I have a javascript button (button A), when it is clicked, it generates some new elements, including another button (button B). I would like a way to listen on button B, and then execute a separate function.
I tried editing Button B's 'onclick' attribute in javascript. This did not work.
HTML:
<input id="addTaskButton" type="submit" value="add task" onclick="addTaskFunction()"></input>
Javascript:
function buttonB()
{
// Not working
}
function addTaskFunction()
{
var doneButton = document.createElement("BUTTON");
doneButton.id = "doneButton";
doneButton.innerHTML = "DONE";
doneButton.onclick = "buttonB()";
}
i am expecting the listener to perform buttonB when ran. Instead, i get no response.
Correct use is as follows
function addTaskFunction()
{
var doneButton = document.createElement("BUTTON");
doneButton.id = "doneButton";
doneButton.innerHTML = "DONE";
doneButton.onclick = buttonB;
}
This works for me:
doneButton.onclick = function(){buttonB()};
I have been trying to find a way to inject a button when a textarea in the window document got clicked(onfocus) ...for weeks, but I failed to do so.
The function is similar as how Grammarly's extension does.
Grammarly's extension
The thing is, I want to add a button nearby or in the textarea when it is onfocus or keypressed. Then I could return the text value to the extension. What is the right way to detect the div in the content script?
the button code is like this:
function appendBtn (){
var btn = document.createElement("INPUT");
btn.setAttribute("type", "button");
btn.setAttribute("value", "button");
document.body.appendChild(btn);
}
document.onclick = function() {
appendBtn();
}
what I want is to find the right div instead of appending the element after body...which it always show at the bottom of the page, especially on facebook page, which I can't even target the input boxes of the comment area..
Please help me with this! I am so desperate right now...
Use the focusin event (it bubbles unlike the focus event) in a content script of your extension:
var btn = createButton();
document.addEventListener('focusin', onFocusIn);
function onFocusIn(event) {
var el = event.target;
if (el.contentEditable ||
el.matches('input, textarea') && el.type.match(/email|number|search|text|url/))
{
appendButton(el);
}
}
function createButton() {
var btn = document.createElement('button');
btn.textContent = 'Yay!';
btn.onclick = function(event) {
btn.textContent += '!';
};
return btn;
}
function appendButton(textElement) {
textElement.parentElement.insertBefore(btn, textElement.nextElementSibling);
}