Javascript Dynamically inserted DOM Element automatically triggers onclick Event - javascript

I have been working an a auto-completion feature for a project that I am working on.
I want the user to be able to click on on of the auto-completions which will query more information about the product.
When assigning a onclick event to that dynamic created DOM element said onclick event automatically triggers.
Now I have reproduced this "error" in a js fiddle:
https://jsfiddle.net/50y4ma8h/2/
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<div id="results">
</div>
</body>
</html>
JS
var resultsElement = document.getElementById("results");
var div = document.createElement("DIV");
div.append("Hey");
div.onclick = querySomething();
resultsElement.innerHTML = div.outerHTML;
function querySomething() {
alert("hey");
}
I do not understand why the function that is assigned to the oncllick event is automatically called.
I would appreciate any Help :)

div.onclick = querySomething();
Is assigning the result of querySomething function to the handler, and not the function itself.
You probably meant:
div.onclick = querySomething;
Also note that moving the innerHTML somewhere else will not bring the bound onclick listener with it, so resultsElement will not have this event attached.

As you don't really append the created div to the resultsElement you can't attach eventListener to it, I change your code a bit.
var resultsElement = document.getElementById("results");
var div = document.createElement("DIV");
div.append("Hey");
div.addEventListener('click', querySomething);
resultsElement.appendChild(div);
function querySomething() {
alert("hey");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
<div id="results">
</div>
</body>
</html>

Related

A text is displayed only right after my javascript is triggered

I wrote javascript codes.
By clicking the button, the child window pops up and displays a text sent from the parent window using a postMessage function.
My code could sent a text to the child window, but there's no text displayed.
The text is displayed only when I keep clicking the button. I don't want the text to disappear.
I think my code is overridden by a blank script or something, though I don't write any other codes except for below.
Do you have any solution for this?
the parent window html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Parent Window</title>
</head>
<body>
<input type="button" value="TEST_BUTTON" id="testButton">
<script>
var testButton = document.getElementById('testButton');
testButton.addEventListener('click', function(event) {
event.preventDefault();
var newWindow = window.open('./child_window.html', 'popupWindow', 'width=400,height=300');
newWindow.postMessage('this is a content from the parent window.', '*');
return false;
},false);
</script>
</body>
</html>
the child window html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Pop Up Window</title>
</head>
<body>
<h1 id="mainText"></h1>
<script type="text/javascript">
var mainText = document.getElementById('mainText');
window.addEventListener('message', function(event) {
console.log(event.data);
this.mainText.innerText = event.data;
}, false)
</script>
</body>
</html>
I ended this up using localStorage instead.

How to attach a click handler with addEventListener

This is the html part of my code:
<!DOCTYPE html>
<html>
<head>
<h>
<title> This page</title>
</h>
</head>
<body>
<button id = "go-button" >GO</button>
<script src="main.js"></script>
</body>
</html>
This is the javaScript part of my code:
function buttonClicked(){
console.log("button clicked");
}
var btn = document.getElementById("go-button");
btn.addEventListener("clicked", buttonClicked);
Whenever i try to print it on console, it does not show any output, i am confused
There is no event clicked but click:
btn.addEventListener("click", buttonClicked);
Correct clicked to click and it should work.
The event name is "click", not "clicked"
The addEventListener function takes two parameters one is the event and second the function to be executed, you have speelled the first parameter wrong.
btn.addEventListener ('click', buttonClicked);

How to add event with Javascript to an html tag

I've a landingpage with dynamic html tags.
The Problem is, that i can't select directly the tag. Its a link.
the following code is the construct:
<div id="testid"><div><div>Button 1<div><div><div>
Every time someone clicks on the link (a-tag) I want to fire an event like the following code:
Button 1
the question: what is the Javascript code to add the onclick="dataLayer.push({'event': 'button1-click'}) attribute to the a tag.
I tried the following code:
var d = document.getElementById("testid").firstchild;
d.setAttribute("onclick", "dataLayer.push({'event': 'button1-click'})");
but it seems to the code is incorrect. The a tag is also not the first child; there are 2 divs between :(
Use querySelector and addEventListener:
document.addEventListener('DOMContentLoaded', function () {
var dataLayer = [];
var d = document.querySelector("#testid a[name=button1]");
d.addEventListener("click", function () {
dataLayer.push({ 'event': 'button1-click' });
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="testid">
<div>
<div>
Button 1
<div>
<div>
<div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="script.js">
</script>
</body>
</html>
There's a few things you were missing from your JS.
Using a more specific selector (#testid a[name=button1] vs. the firstchild of #testid, which was not accurate).
Wrapping all the code in a DOMContentLoaded listener. JS that depends on elements on a page needs to wait for the page to build first, that's what DOMContentLoaded is.
Check out my solution. Hope this helps.
var d = document.querySelector("#testid a");
var dataLayer = []
d.onclick = function () {
dataLayer.push({'event': 'button1-click'})
console.log(dataLayer.length)
}
<div id="testid"><div><div>Button 1<div><div><div>

How to use external Javascript to use onclick event to change document.title?

This code runs immediately once the page is loaded. The onclick event is completely ignored by javascript. What is an easy fix for this because like youtube when you play a video the document.title is updated with a speaker. I want to learn to do that with external javascript because I can do it with internal javascript in the html.
<!DOCTYPE html>
<html>
<head>
<title> Animation </title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="animationcss.css">
</head>
<body>
<script src="animation.js"></script>
<input id="changeButton" type="button" value="Change" ></input>
/External Javascript/
var element = document.getElementById("changeButton");
element.onclick = textChange("changetothis");
function textChange(text){
document.title = text;
}
try calling the function after the document is loaded by placing the script tag below the object or making $(document).ready() function,
this code works fine with me
<!DOCTYPE html>
<html>
<head>
<title> Animation </title>
<meta charset="UTF-8">
</head>
<body>
<input id="changeButton" type="button" value="Change" ></input>
<script src="script.js"></script>
<body>
</html>
and the script is
var el = document.getElementById("changeButton");
el.onclick = function(){
textChange("changetothis");
}
function textChange(text){
document.title = text;
}
You can achieve your desired effect by using an anonymous function, like so:
document.getElementById("changeButton").onclick = function () {
document.title = newTitle;
}
The variable 'newTitle' should be declared & initalized above this code somewhere in order for it to work.

getElementsByTagName is not working Simple JS

another quesion: http://jsfiddle.net/ajinkyax/qGzTY/1/
Above link shows a js calculator, but whn u click nothign happens
Im just amazed why this simple function not working!!!.
I even tested with a tag, still it wont wokr. getElementsByTagName("a")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>documentElement</title>
</head>
<body>
<p>This is 4rth child (3)</p>
<p>This is 4rth child (3)</p>
<p>This is 5th child (4) <span id="some">CHANGE THIS</span></p>
<script type="text/javascript">
var mySpan = document.getElementsByTagName('span');
mySpan.innerHTML = 'This is should change';
</script>
</body>
</html>
Do this :
var mySpan = document.getElementsByTagName('span')[0];
mySpan.innerHTML = 'This is should change';
getElementsByTagName doesn't return an element but a collection of all elements having this tag name. If you want only the first one, add [0].
As was pointed by user1689607, if you want to change just this specific span, you'd better do
var mySpan = document.getElementById('some');

Categories

Resources