Detecting a click after a new element is loaded after the DOM - javascript

I am trying to create a simple Chrome Plugin - however I have come to an issue.
I am trying to detect a click on a div using a simple getElementById - however as the api call happens after the DOM is loaded the JS cannot 'find' any div's and gives an error and doesn't do anything after I click on the element.
How do I detect the click, after the data from the API has loaded? I have included some of my code below:
Thanks
document.addEventListener('DOMContentLoaded', function () {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function () {
inputBox = document.getElementById("postcodeInput").value
console.log(inputBox)
let xml = new XMLHttpRequest();
xml.open('get', "https://api.getaddress.io/find/" + inputBox + "/?api-key=SECRET&expand=true", false);
xml.send(null);
var data = xml
var arr = xml.responseText
var data = JSON.parse(arr)
var postcode = data.postcode
var addresses = data.addresses
console.log(addresses)
document.getElementById("postcode").innerHTML = postcode;
var text = "";
var i;
for (i = 0; i < addresses.length; i++) {
text += "<div id='addressClick' name=" + i + ">" + addresses[i].line_1 + "</div>" + "<br>";
}
document.getElementById("data").innerHTML = text;
clickFunc()
}, false);
}, false);
function clickFunc() {
var rowBox = document.getElementById("addressClick");
rowBox.addEventListener('click', function () {
console.log('asd');
}, true);
}
HTML
<!doctype html>
<html>
<head>
<title>Address Search</title>
<script src="popup.js"></script>
</head>
<body>
<h3>Address Search</h3>
<input type="text" id='postcodeInput' name="postcodeInput" value="KW1 4YT">
<button id="checkPage">Search</button>
<div class='results'>
<h3>Results - <span id='postcode'></span></h3>
<p id='data'></p>
</div>
</body>
</html>
<style>
body {
width: 200px
}
#addressClick:hover {
color: blue;
cursor: pointer
}
</style>

You can attach an EventListener to all the body and, at every click, detect if the clicked element is the desired one:
document.body.addEventListener('click', event => window.alert(event.target.innerText));
This can sound like an aggressive solution, but it's way less invasive than a MutationObserver

Related

Add element to website/tab from Safari extension

I am trying to create an extension for Safari that will add an element to the page/tab that I am currently on. In the example below I'd like to add the Send button to the page.
The issue for me is that the new element (button) will be added to the extensions html.
Html:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function sendMessage() {
document.getElementById("textField").innerHTML="Sending message...";
safari.application.activeBrowserWindow.activeTab.page.dispatchMessage("hey", "there");
}
function respondToMessage(messageEvent) {
if(messageEvent.name === "gotIt")
document.getElementById("textField").innerHTML=messageEvent.message;
}
safari.self.browserWindow.addEventListener("message",respondToMessage,false);
</script>
</head>
<body> Message Sender Bar
<input type="button" value="Send" onclick="sendMessage()" >
<span id="textField">...waiting... </span>
</body>
</html>
Js:
var theBody = document.body;
var element = document.createElement("p");
element.id = "status";
element.style.cssText = "float:right; color:red";
element.textContent = "Waiting...";
theBody.insertBefore(element, theBody.firstChild);
function replyToMessage(aMessageEvent) {
if (aMessageEvent.name === "hey") {
document.getElementById("status").textContent="Message received.";
safari.self.tab.dispatchMessage("gotIt","Message acknowledged.");
}
}
safari.self.addEventListener("message", replyToMessage, false);

element is getting variable without declared

I am having a JavaScript code that is having a value in #message but i have not defined anywhere.
Does $("#message").html(result); is something inbuilt in Javascript?
I apologize if it is very basic and stupid question.
It is linked to my another question "
https://stackoverflow.com/questions/41745209/save-javascript-value-when-converting-speech-to-text-via-webkitspeechrecognition#
Complete Code
<!DOCTYPE html>
<html>
<head>
<script src="Content/SpeechScript.js"></script>
<title>Login Screen</title>
<meta charset="utf-8" />
</head>
<body >
<div id="results">
<span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<script type="text/javascript">
function Typer(callback) {
speak('Welcome ,Please Speak your CPR Number');
var srcText = 'WelcomeToDanske,PleaseSpeakyourCPR Numberwhat';
var i = 0;
debugger;
var result = srcText[i];
var interval = setInterval(function () {
if (i == srcText.length - 1) {
clearInterval(interval);
callback();
return;
}
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html(result);
debugger;
document.getElementById('user').innerHTML = result;
// var parent = document.getElementById('parentDiv');
// var text = document.createTextNode('the text');
// var child = document.getElementById('parent');
// child.parentNode.insertBefore(text, child);
// var div = document.getElementById('childDiv');
//var parent = document.getElementById('parentDiv');
//var sibling = document.getElementById('childDiv');
////var text = document.createTextNode('new text');
// //parent.insertBefore(result, sibling);
},
100);
return true;
}
function playBGM() {
startDictation(event);
}
Typer(function () {
playBGM();
});
// say a message
function speak(text, callback) {
var u = new SpeechSynthesisUtterance();
u.text = text;
u.lang = 'en-US';
u.onend = function () {
if (callback) {
callback();
}
};
u.onerror = function (e) {
if (callback) {
callback(e);
}
};
speechSynthesis.speak(u);
}
</script>
</div>
<div id="clockDisplay">
<span id="id1">Welcome:</span>
<table width="100%" border="1"><tr><td width="50%"> Username : </td><td><div id="message"></div></td></tr></table>
</body>
</html>
$("#message").html(result); is something inbuilt in Javascript?
No.
$ is a variable that is no part of the JavaScript spec, nor is it part of the common extensions to JS provided by browsers in webpages. It is commonly used by libraries such as PrototypeJS and jQuery. This particular case looks like jQuery, but you aren't including that library in your page.
Fist off, remember to include jQuery as script in your html document or $ will not be defined.
#message Refers to an element in your html document with the tag of id="message"
To get an element in jQuery, by id, you use this syntax: var Element = $("#ID");
So, to make sure your code works, ensure that both there is an element with the ID message, and a defined variable named result containing the html text to put into your element.
Since you want to append to <div id="clockDisplay"> <span id="user">Username :</span></div>, why not change it to:
<div id="clockDisplay">
<span id="user">Username :</span>
<div id="message"></div>
</div>

Cannot set property 'innerHTML' of null while still using window.onload to delay

I am trying to write a script that changes the color of the text if it is an active screen (there are probably more efficient ways to do this). The error I am getting is Uncaught TypeError: Cannot set property 'innerHTML' of null My JavaScript (the entire page)
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
main();
The HTML
<!DOCTYPE html>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<html>
<head>
<title>
</title>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script src="../scripts/essentials.js"></script>
</body>
</html>
The IDE (Visual Studio 2015 Cordova) says that the error is on this line in the JavaScript "var cardDivPrint = cardDiv + card + closer;" I have looked at multiple similar problems and applied what was relevant (also tried changing window.onload to document.onload) but it still throws the same error.
onload expects function to be executed after page is completely loaded. Otherwise it'll treat it as simple assignment statement and execute. Use function as follow:
window.onload = function() {
document.getElementById("header").innerHTML = cardDivPrint;
};
UPDATE
Instead of using main(), use DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = window.location.href.indexOf(Check) !== -1 ? "red" : "white";
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
document.getElementById("header").innerHTML = cardDivPrint;
});
Call the main function at the end of your body content
You are getting this error just because the element dose not exists at the time of its selection by JS DOM
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<script>
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
</script>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script>main();</script>
</body>
</html>

jQuery : Using buttons generated by a plugin to interact with

i'm beginner in jQuery Plugin's coding.
I've coded a plugin to generate a Gantt's calendar but i can't succeed with interacting with it.
The code is too long to be posted so i've coded a sample of what a need in kind of interaction.
Here is a sample code that generate a counter and two buttons to increase or decrease the value of the counter.
So the question is : How can i make the button increase / decrease the counter and of course refresh display.
Thanks,
[EDIT]
I explain again what i want to do :
- The buttons are generated by the plugin.
- When they are clicked, they increase/decrease the value and refresh display
- I dont want an external action binding.
- The plugin must be standalone
[/EDIT]
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2">
<title></title>
<link rel="stylesheet" href="/styles/jquery-ui.css" type="text/css">
<script src="/scripts/jquery.js"></script>
<script src="/scripts/jquery-ui.js"></script>
<script>
(function($){
$.fn.mySample = function() {
var _myCount = 0;
this.initialize = function ()
{
this.html('<input type="button" value="--">Count : ' + _myCount + '<input type="button" value="++">');
}
return this.initialize();
}
})(jQuery);
$(document).ready(
function()
{
$('#myDiv').mySample();
}
);
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
Sorry for my first answer :)
So here is your mySample plugin working as a standalone
http://jsfiddle.net/P4p3m/2/
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2">
<title></title>
<script src="jquery-1.11.0.min.js"></script>
<script>
(function($){
$.fn.mySample = function() {
this._counter = 0; // Your counter
this.initialize = function (config)
{
// Get the context of the outside
var context = this;
// Init the -- button
var inputMinus = document.createElement("input");
inputMinus.type = "button";
inputMinus.value = "--";
$(inputMinus).click(function(){
context.updateCounter(-1);
});
this.append(inputMinus);
// Init the display
var spanDisplay = document.createElement("span");
context.spanDisplay = spanDisplay;
$(spanDisplay).text(context._counter);
this.append(spanDisplay);
// Init the ++ button
var inputPlus = document.createElement("input");
inputPlus.type = "button";
inputPlus.value = "++";
$(inputPlus).click(function(){
context.updateCounter(+1);
});
this.append(inputPlus);
}
// Updating the counter value and the display
this.updateCounter = function(nbr){
this._counter += nbr;
$(this.spanDisplay).html(this._counter);
};
// Start the plugin
return this.initialize();
}
})(jQuery);
$(document).ready(
function()
{
$('#myDiv').mySample();
}
);
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
I modified your code to add id's to better identify the buttons and a span to identify where we want to modify the count:
Here's the updated code to reflect your comments, along with the code working in a fiddle: http://jsfiddle.net/XMgz4/
(function ($) {
$.fn.mySample = function () {
var _myCount = 0;
var inputStr = '<input id="decButton" type="button" value="--">'
+ 'Count : <span id="count">' + _myCount
+ '</span><input id="incButton" type="button" value="++">';
this.html(inputStr);
this.find("#decButton").on("click", function() {
_myCount --;
$("#count").text(_myCount);
});
this.find("#incButton").on("click", function() {
_myCount ++;
$("#count").text(_myCount);
});
}
})(jQuery);
You will need to put the Count : ' + _myCount + ' inside an element.. like this:
'Count : <div id="result">' + _myCount + '</div>'
After that you will create a function to get the value of result.. like this $('#result').html()
and increase or decrease the value using onclick event of your inputs... (You must to add class or id for your inputs...)
I will suppose that the id is btnDecrease and btnIncrease... You will need to do something like this:
$('#btnDecrease').on('click', function(){
$('#result').html(parseInt($('#result').html()) - 1);
});
and
$('#btnIncrease').on('click', function(){
$('#result').html(parseInt($('#result').html()) + 1);
});
Hope it helps

Creating an option menu based on a text file?

I am trying to automatically create an option menu (using HTML and JavaScript) based on the contents of a text file. What I would like is for each option in the menu to be a line in the text document.
Here is the JavaScript:
function get_parameters() {
alert("get_parameters() called"); // these alerts are just to tell me if that section of the code runs
var freader = new FileReader();
var text = "start";
freader.onload = function(e) {
text = freader.result;
alert('file has been read');
}
freader.onerror = function(e) {
alert('freader encountered an error')
}
freader.readAsText('./test.txt', "ISO-8859-1");
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
}
With this code, all I'm trying to accomplish is reading the file and printing to the div "bottom_pane_options" but I can't find any reason why it doesn't work. If my way isn't the most efficient, could you please give me code that would work?
Thanks.
--EDIT--
Here is the HTML
<!DOCTYPE html>
<html>
<head>
<title>Culminating</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
</script>
<script>
// Calling the Google Maps API
</script>
</head>
<body>
<div class="content">
<div id="googleMap"></div>
<div id="right_pane_results">hi</div>
<div id="bottom_pane_options">
<button onclick="get_parameters()">Try It</button>
</div>
</div>
</body>
<script type="text/javascript" src="./javascript.js"></script>
</html>
You need to set the <div> text in the callback instead of right after you start loading:
freader.onload = function(e) {
text = freader.result;
/*************
** TO HERE **
************/
alert('file has been read');
}
/* MOVE THIS */
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
/*************/
Because the file was not read yet when you are runing div.innerHTML = div.innerHTML + text;.
That's why there are callbacks.
See https://developer.mozilla.org/en-US/docs/Web/API/FileReader :
The FileReader object lets web applications asynchronously read the
contents of files [...]
Use this instead :
freader.onload = function(e) {
text = freader.result;
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
alert('file has been read');
}
freader.onerror = function(e) {
alert('freader encountered an error')
}
freader.readAsText('./test.txt', "ISO-8859-1");

Categories