Why is the button disapearing? - javascript

The text "Now I'm here..." is supposed to disappear when the button is clicked, not the button itself.
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="remove()">Remove</button>
<script>
function remove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
/*function add()
{
var ele = document.createElement("p");
var text = document.createTextNode("This is new text");
ele.appendChild(text);
var location = document.getElementById("alpha");
location.appendChild(ele);
}*/
</script>

There is another function called remove that is interfering with your function.
Rename your function and it works fine:
http://jsfiddle.net/fL3gZ/
<div id="alpha">Now I'm here...</div>
<button type="button" onclick="Myremove()">Remove</button>
<script>
function Myremove()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}
</script>

What's happening is remove() is being called on the button itself! HTMLElement.prototype.remove is an existing function (in some browsers)! Oh god!
var button = document.getElementsByTagName("button")[0];
// surprise! this is what's actually happening
button.remove();
Check out this alternative approach. See: fiddle
Change HTML to
<div id="alpha">Now I'm here...</div>
<button type="button">Remove</button>
Then use this JavaScript
function remove(id) {
var elem = document.getElementById(id);
if (elem) elem.parentNode.removeChild(elem);
}
var button = document.getElementsByTagName("button")[0];
button.addEventListener("click", function(event) {
remove("alpha");
event.preventDefault();
});
A couple things about this:
I'm favoring a more unobtrusive approach
The remove function is single purpose, and reusable
It will work in more browsers
You won't run into WTFs like you just experienced

remove() is already an excisting javascript method, so you are actually calling that method on your button instead of calling the function.
Just rename the function and it will be fine.
Fiddle: http://jsfiddle.net/WkUqT/7/
function removeText()
{
var element = document.getElementById("alpha");
element.parentNode.removeChild(element);
}

You are probably using chrome as your browser to test that code. Elements in chrome have a self-removal, .remove() method which removes the element itself from its container.
This is the main reason why the code above removes the button, because of this the appended event in your onclick() declaration was not invoked because the element invoking the event does not exist anymore. Try changing the name of your function to removeElement().

Related

Add click event on a dynamically created element in Javascript

I am trying to add a click event on an element which i create dynamically in Vanilla JS. With jquery its super simple all i would do is
$(document).on('click','.el', function() {
//somecode
})
However with Vanilla JS (because i'm using react) i can't do the same thing.
I've tried adding the dynamic element as an argument just like i would in jquery but no money.
I'm sure it can be done just not the way i'm thinking. Any ideas?
I tried
let div = document.createElement('DIV')
div.classList.add('el')
document.addEventListener('click','.el', function() {
//some code
})
I also tried
document.addEventListener('click',div, function() {
//some code
})
None of these methods worked
let div = document.createElement('DIV');
div.classList.add(".whatever");
div.addEventListener('click', function() {
console.log('dynamic elements')
});
document.body.appendChild(div);
https://jsfiddle.net/yu1kchLf/
You could simply use and onclick function and just call it as variable from your dynamically added elements.
Live Demo
//Create function
let button = document.createElement('button');
button.classList.add("myBtn");
button.innerText = 'Click Me';
button.onclick = myFunction //assign a function as onclick attr
document.body.appendChild(button);
//Call function
function myFunction() {
console.log('I am being called from dynamically created button')
}
i think what you are missing is appending the element you created to your DOM.
have a look at this:
var createDiv = function() {
let div = document.createElement('DIV');
div.id = 'el';
div.innerHTML = '<b>hey</b>';
div.classList.add('styles');
document.body.appendChild(div);
div.addEventListener('click', function() {
alert('Look here');
})
};
here's a fiddle so you can playaround: https://jsfiddle.net/khushboo097/e6wrLnj9/32/
You can do something like the following:
const d=document.getElementById("container");
document.addEventListener('click', function(ev) {
if (ev.target?.classList.contains('el')) {
console.log("My .el element was clicked!");
ev.target.classList.contains("segundo") &&
(d.innerHTML+='<p class="el">another clickable paragraph</>');
}
})
<div id="container"><h2>Something unclickable</h2>
<p class="el primero">A clickable paragraph!</p>
<p class="otro primero">something unclickable again ...</p>
<button class="el segundo">add clickable element</button>
</div>
The event handler is attached to the document itself but will only fire the console.log() if the ev.target, i. e. the clicked element, is of class "el".

toggle class on click Javascript

I want to know WHY its not working.
I have a bunch of classes called yellow.
I then add an event listener to them with a callback function to activate upon clicking. What am I not seeing here? :(
function test(){
var allYellow = document.querySelector('.yellow');
allYellow.addEventListener('click', function(){
this.classList.toggle = 'testyellow';
})
}
test();
In JavaScript..
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.toggle("mystyle");
}

How can we pass an element to event handler in javascript

I have created an <input> HTML element using Javascript. Now I want to add an onblur event handler to this element dynamically. However I do not understand how I can pass the created element as an argument to the function. Here's my code:
element = document.createElement("input");
element.onblur = hello_function;
In the above code you can see that the element is created. Now I want to pass that element to hello_function. How can I do that?
function hello_function(element) {
alert(element);
}
To achieve this you can wrap the hello_function call in an anonymous function wrapper and provide the this argument:
element = document.createElement("input");
element.addEventListener('blur', function() {
hello_function(this);
});
document.body.appendChild(element);
function hello_function(element) {
console.log(element);
}
Also note the preferred use of addEventListener over onblur.
try like this. passing the another variable into a function,
var something="hello";
var element = document.createElement("input");
element.addEventListener('blur' , function ()
{
hello_function(something);
})
document.body.appendChild(element)
function hello_function (element){
alert(element);
}
i suggest to use addEventListener, also i think you need to append the created element to the document, something like this:
var elem = document.createElement("input");
if (elem) {
elem.addEventListener('blur', hello_function, false);
}
document.body.append(elem);
function hello_function(element) {
alert(element);
}

How to reference button in jQuery?

In the HTML, I have a button defined like this:
<button type="button" onclick="toggleEdit();">Edit</button>
At the end of the page, I have this script I am working on:
<script language="JavaScript">
<!--
function toggleEdit() {
var btn = $(this);
var li = btn.parent();
var textArea = li.children('.readOnly');
...
}
//-->
</script>
I cannot reference the button I have clicked in the script. The btn variable is an object, but I don't know anything else than that.
I found many examples on the internet that are using this approach:
$(document).ready(function () {
$('#buttonID').click(function () {
...
but I cannot reference the button via ID because it is added dynamically. So, how do I reference it? Thanks.
Just to keep it your way, you have to tell the code that this will refer to the button instead of the actual function.
To do this you can just add an extra argument to the toggleEdit function.
The new HTML would look like this (no apply or call function needed):
<button type="button" onclick="toggleEdit(this);">Edit</button>
Then your new JavaScript would look like this:
<script language="JavaScript">
<!--
function toggleEdit(t) {
var btn = $(t);
var li = btn.parent();
var textArea = li.children('.readOnly');
...
}
//-->
</script>
You can pass the event into the function, and then use that.
<button type="button" onclick="toggleEdit( event );">Edit</button>
Then in your function, you can get the target of the event:
function toggleEdit( e ) {
var btn = $( e.target );
var li = btn.parent();
var textArea = li.children('.readOnly');
...
}

How can I add an onclick handler on a dynamic element?

Here is the important part of my JS code:
function createClose() {
var cButton = document.createElement("img");
cButton.src = "close.gif";
cButton.style.cursor = "pointer";
cButton.onclick = closeWindow;
document.getElementById("my_window").appendChild(cButton);
}
function closeWindow() {
document.getElementById("my_window").style.display = "none";
}
The image gets created and appended, but there is no onClick event invoked when it is clicked. I also tried using an anonymous function, but that didn't work either.
No, I'm not going to use jQuery (although I believe you that it's easier).
input.setAttribute('onclick','handleClick();');
input = document.getElementById("my_window").appendChild(cButton);
input.onclick = function() { yourFunction(); };
This question is almost a duplicate of "Add onclick property to input with JavaScript"
As an alternative way I've seen the use of input.setAttribute('onclick', 'yourFunction();'); too but cannot guarantee it works.

Categories

Resources