DOMContentLoaded is not firing - dom

I am trying to create a chrome extension but having problems with DOMContentLoaded as it is not firing.
Note: my code was taken from a different website.
Basically, I have create an HTML file with a button:
<head>
<title>GTmetrix Analyzer</title>
<script src="popup.js"></script>
</head>
<body>
<h1>GTmetrix Analyzer</h1>
<button id="checkPage">Check this page
now!</button>
</body>
And this is the JS file (popup.js):
document.addEventListener
('DOMContentLoaded',
function() {
console.log("f")
var checkPageButton =
document.getElementById('checkPage');
checkPageButton.addEventListener('click',
function() {
chrome.tabs.getSelected(null,
function(tab) {
d = document;
var f = d.createElement('form');
f.action = 'http://gtmetrix.com/analyze.html?bm';
f.method = 'post';
var i = d.createElement('input');
i.type = 'hidden';
i.name = 'url';
i.value = tab.url;
f.appendChild(i);
d.body.appendChild(f);
f.submit();
});
}, false);
}, false);
I added the console.log event in order to check if the event is executed, so this is how I verified that it isn't working.
I also added run_at": "document_start
but then I got
Uncaught TypeError: Cannot read property 'addEventListener' of null
For the "click" event, so I guess that the event was triggered before the button was created.
Help, please!

Related

Date Picker work without internet

I need to use a date picker to work without internet.
I have changed my source links from https links to downloaded files in my local. But then Date picker stops working.
Can someone please let me know how to overcome this issue?
ideal source links :
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
Changed to locally downloaded files
<script src = "jquery-ui.js"></script>
<script src = "jquery-1.10.2.js"></script>
<script src = "jquery-ui.css"></script>
I shall be good if I can assure that even if https links used, it will work fine for my date pickers when internet is not there. Might be through some caching.
Updating my Question with datepickers code:
<span style="float: left;margin-left:2em"> <b>Date Range: </b>
<input type="text" id="datepicker" > <b>to </b>
<input type="text" id="datepicker2"> </span><div id = "Alert" style="float:left;margin-left:2em"> Please select a valid Date Range!</div>
.............................................
var startDate;
var endDate;
var start;
var end;
$(function() {
$("#datepicker").datepicker({
onSelect: function() {
startDate = $(this).datepicker('getDate');
start = formatDate(startDate);
if( start!=null && end!=null && end>=start)
{document.getElementById('Alert').style.visibility = 'hidden';
document.getElementById('canvas-holder').style.visibility = 'visible';
initial(start, end);
}
else {
document.getElementById('Alert').style.visibility = 'visible'; //Will show
document.getElementById('canvas-holder').style.visibility = 'hidden';
}
}
});
$("#datepicker2").datepicker({
onSelect: function() {
endDate = $(this).datepicker('getDate');
end = formatDate(endDate);
alert('skn here s' + startDate);
alert('skn here e' + endDate);
if( start!=null && end!=null && end>=start)
{document.getElementById('Alert').style.visibility = 'hidden';
document.getElementById('canvas-holder').style.visibility = 'visible';
initial(start, end);
}
else {
document.getElementById('Alert').style.visibility = 'visible'; //Will show
document.getElementById('canvas-holder').style.visibility = 'hidden';
}
}
});
});
Please find below error I get in browser console.
Uncaught TypeError: $(...).datepicker is not a function
at HTMLDocument.<anonymous> (index.html:64)
at fire (jquery-1.10.2.js:3048)
at Object.fireWith [as resolveWith] (jquery-1.10.2.js:3160)
at Function.ready (jquery-1.10.2.js:433)
at HTMLDocument.completed (jquery-1.10.2.js:104)
I have incorporated changes as suggested. In that case date picker shows but not as expected.
Date PickerIssue:
Date Picker Expected
try changing this to
<link href = "jquery-ui.css" rel = "stylesheet">
<script src = "jquery-1.10.2.js"></script>
<script src = "jquery-ui.js"></script>
you need to load jquery before jquery-ui.js

Dropzone - multiple instances get id

I have multiple dropzone forms
<form action="/upload" class="dropzone" id="group1"></form>
<form action="/upload" class="dropzone" id="group2"></form>
<form action="/upload" class="dropzone" id="group3"></form>
How do I get the id of the form the file is dropped into?
To hook into a Dropzone action like a file being added, you'll need to use an event handler. From the docs:
Dropzone triggers events when processing files, to which you can register easily, by calling .on(eventName, callbackFunction) on your instance.
So you'll need to manually instantiate your Dropzones, to get access to the instance.
If you're using jQuery:
// Don't automatically instantiate, we'll do it manually
Dropzone.autoDiscover = false;
// Using the jQuery syntax shown in the docs
$("#group1, #group2, #group3").dropzone({
init: function() {
var formID = this.element.attributes.id;
this.on("addedfile", function(file) {
console.log('Image dropped on form ID', formID);
});
}
});
If you're not using jQuery:
Dropzone.autoDiscover = false;
var dz = [],
forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; i++) {
dz[i] = new Dropzone(forms[i], {
init: function() {
var formID = this.element.attributes.id;
this.on("addedfile", function(file) {
console.log('Image dropped on form', formID);
});
}
});
}

Crossrider API not ready to receive events?

I'm trying to trigger an event on my crossrider extension. Using the code below the event never gets to the extension. If I put a timeout and wait 5 seconds it does. So is there a way to detect when the extension\api is ready to receive events?
$(document).ready(function () {
var x = 'xxxxx';
$('body').fireExtensionEvent('eventName', { key: 'token-' + x });
});
You can use CrossriderAPI.isAppInstalled.
<script type="text/javascript" src="https://w9u6a2p6.ssl.hwcdn.net/plugins/javascripts/crossriderAPI.js"></script>
<script type="text/javascript">
// Replace XXXXX with the extension id
var extId = "XXXXX";
// Once the page is ready
$(function() {
CrossriderAPI.isAppInstalled(extId, function(isInstalled) {
// Displays true if the extension is installed; otherwise false
var x = 'xxxxx';
$('body').fireExtensionEvent('eventName', { key: 'token-' + x });
});
});
</script>
[Disclosure: I am a Crossrider employee]

React onClick keeps triggering

When I trigger the onClick even the event keeps triggering for about 1000+ times. I can't seem to figure where this is coming from. I have changed the onClick to an onMouseover to see if it keeps triggering but then the event only triggers once.
I'm using : react 0.13.3
Any idea's?
var React = require('react');
var AppActions = require('../../actions/app-actions.js');
var FileAmount = React.createClass({
getInitialState: function() {
return {
amount : this.props.amount,
config : this.props.config
};
},
handleClick: function(e){
var name = e.target.name;
if(name === 'decrease'){
if(this.state.amount > 1){
this.setState({
amount : (this.state.amount - 1)
});
AppActions.updateAmount(this.props.index, (this.state.amount - 1))
}
}else{
this.setState({
amount : (this.state.amount + 1)
});
AppActions.updateAmount(this.props.index, (this.state.amount + 1))
}
},
handleChange: function(e){
var amount = e.target.value;
this.setState({
amount : amount
});
AppActions.updateAmount(this.props.index, amount)
},
render: function() {
var config = this.state.config
return (
<div className="file-amount">
<span className="file-amount-text"> {config.filelist_quantity}: {this.state.amount} {config.filelist_pieces}</span>
<div className="file-amount-fields">
<i className="file-amount-decrease icon" name="decrease" onClick={this.handleClick} />
<input className="file-amount-input" type="number" value={this.state.amount} onChange={this.handleChange} />
<i className="file-amount-increase icon" name="increase" onClick={this.handleClick} />
</div>
</div>
);
}
});
module.exports = FileAmount;
I left a comment on the original post, but on second inspection, it looks quite possible that you pass down props.amount from a Flux Store. If that is the case you're creating an infinite loop.
handleClick increments state.amount, then after the AppAction is called, the Store updates the component with props.amount, then the onChange fires because it is tied to state.amount and then onChange changes state.amount and changes props.amount when it calls AppActions.updateAmount.
Every time props or state are updated, React will call the render() method. If there is any way that props or state get updated while the render() executes, then you are likely going to run into an infinite loop.
Perhaps adding a e.preventDefault(); to your handleClick method will stop this loop from being started.
I removed the added javascript for the browser-sync proxy settings. That somehow screwed around with my react.

detect dynamically checkboxes/polymer elements ticked in Dart

A newbie to Dart with no experience in JS.
I have written code to populate a dropdown from JSON.
Edit:
i am trying to add polymer elements.
Polymer .dart
import 'package:polymer/polymer.dart';
#CustomTag('player-item')
class PlayerItem extends PolymerElement{
#observable String playerName='hello';
void removePlayer(){
playerName='';
}
PlayerItem.created(): super.created(){}
}
Initially was getting error of constructor not defined. added empty brackets to
super.created. error fixed
What am i doing wrong. how to do this correctly??
polymer.html
playername = name of player to be displayed dynamically.
right now using default string.
removeplayer = (ideas is to) remove entire polymer element.
<polymer-element name="player-item">
<template>
<input type="image" src="button_minus_red.gif" on-click="{{removePlayer}}">
<div>{{playerName}}</div>
</template>
<script type="application/dart" src="player-item.dart"></script>
</polymer-element>
Edited Dart Code:
Objective is first generate options then select one of them and the subsequently remove them if clicked on image(polymer element intended for this purpose).
Went through polymer example master. but couldnt find something related.
Help Needed:
1. how do i dynamically add polymer elements?
how to pass values (ie. in this case name of player) to the dynamically added
polymer element?
how to remove polymer elements?
How to remove appended text added via *.appendedtext ?
import 'dart:html';
import 'dart:convert' show JSON;
import 'dart:async' show Future;
import 'package:polymer/polymer.dart';
import 'player-item.dart';
//ButtonElement genButton,desButton;
SelectElement selectTeam;
FormElement teamPlayer;
FormElement yourPlayer;
InputElement teamPlayers;
//final subscriptions = <StreamSubscription>[];
List<String>teams=[];
List<String>players=[];
main() async{
selectTeam = querySelector('#teamNames');
teamPlayer = querySelector('#teamPlayers');
yourPlayer = querySelector('#yourPlayers');
selectTeam.onChange.listen(populateTeams);
try {
await prepareTeams1 ();
selectTeam.disabled = false; //enable
//genButton.disabled = false;
} catch(arrr) {
print('Error initializing team names: $arrr');
}
}
void populateYourPlayers(String name){
querySelector('#yourPlayers').children.add(new Element.tag('player-item'));
var input = new InputElement();
input.type = "image";
input.src = "button_minus_red.gif";
input.id = name;
print('yo');
input.width = 15;
input.height =15;
input.appendText(name);
input.onClick.listen((remove){
remove.preventDefault();
input.remove();
//yourPlayer.children.remove();
});
yourPlayer.append(input);
// yourPlayer.append(y);
yourPlayer.appendText(name);
yourPlayer.appendHtml("<br>");
}
void removeYourPlayers(Event e){
yourPlayer.querySelectorAll("input[type=checkbox]").forEach((cb) {
// print('${cb.checked}');
if(cb.checked == true){
print('${cb.id}');
yourPlayer.children.removeWhere((cb)=>cb.checked==true);
}
}
);
}
Future prepareTeams1()async{
String path = 'teams.json';
String jsonString = await HttpRequest.getString(path);
parseTeamNamesFromJSON(jsonString);
}
parseTeamNamesFromJSON(String jsonString){
Map team = JSON.decode(jsonString);
teams = team['Teams'];
print(teams);
for (int i =0; i< teams.length; i++){
var option = new OptionElement();
option.value = teams[i];
option.label =teams[i];
option.selected = false;
selectTeam.append(option);
}
}
Future prepareTeams2(String Team)async{
String path = 'teams.json';
String jsonString = await HttpRequest.getString(path);
parsePlayerNamesFromJSON(jsonString, Team);
}
parsePlayerNamesFromJSON(String jsonString,String Team){
Map team = JSON.decode(jsonString);
teamPlayer.children.clear();
teams = team[Team];
print(teams);
for (int i =0; i< teams.length; i++){
var input = new InputElement(type:"image");
// input.type = "image";
input.id = teams[i];
input.src = "button_plus_green.gif";
input.width = 15;
input.height =15;
input.onClick.listen((p){
p.preventDefault();
populateYourPlayers(teams[i]);
});
//input.onClick.listen((event){populateYourPlayers(teams[i]);});
//subscription.cancel();
teamPlayer.append(input);
teamPlayer.appendText(teams[i]);
teamPlayer.appendHtml("<br>");
}
}
void populateTeams(Event e){
print('selectTeam.length: ${selectTeam.length}');
print(selectTeam.value);
prepareTeams2(selectTeam.value);
if (selectTeam.length == 0){
}
}
Modified HTML:
<html>
<head>
<meta charset="utf-8">
<title>Pirate badge</title>
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="piratebadge.css">
<link rel="import" href="player-item.html">
</head>
<body>
<h1>Team Names</h1>
<select id="teamNames">
</select>
<h1>Team players</h1>
<form id="teamPlayers">
</form>
<div>
<button id="generateButton" disabled>Add Player/Players</button>
</div>
<h1>Your players</h1>
<form id="yourPlayers">
</form>
<player-item></player-item>
<div>
<button id="destroyButton" disabled>Remove Player/Players</button>
</div>
<script type="application/dart" src="piratebadge.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
and based on that selection display a form with checkboxes.
The issue i am facing is how to detect them which checkboxes have been checked and if so how the value of that checkbox can be captured.
Possible duplicate
How to know if a checkbox or radio button is checked in Dart?
However them checkboxes not dynamically created.
If the above approach is wrong, kindly advise.
Depending on when you want to detect the checked state there are two ways.
You can add a click handler to the submit button and then query the checkboxes.
querySelector("input[type=submit]").onClick.listen((e) {
querySelectorAll("input[type=checkbox]").forEach((cb) {
print('${cb.id} {cb.checked}');
});
});
Currently you are assigning the same id to each checkbox. This is a bad choice because you have no way to know which checkbox represents what item.
Another way is to assign a click handler to each checkbox to get notified immediately when the checkbox is clicked.
(I simplified your checkbox creation code a bit by using continuations and forEach instead of for)
teams.forEach((team) {
var input = new InputElement()
..type = "checkbox"
..id = "player"
..onClick.listen((e) {
print('${cb.id} {cb.checked}');
});
teamplayer
..append(input)
..appendText(team)
..appendHtml("<br>");
}
In this case you might need to reset the click notifications when the selection changes.
import 'dart:async';
// ...
final subscriptions = <StreamSubscription>[];
// ...
subscriptions
..forEach((s) => s.cancel())
..clear();
teams.forEach((team) {
var input = new InputElement()
..type = "checkbox"
..id = "player";
subscriptions.add(input.onClick.listen((e) {
print('${cb.id} {cb.checked}');
}));
teamplayer
..append(input)
..appendText(team)
..appendHtml("<br>");
}
Caution: code not tested and it's a while I used checkboxes.
You can read the checked property of the CheckboxInputElement
parsePlayerNamesFromJSON(String jsonString,String Team){
Map team = JSON.decode(jsonString);
teams = team[Team];
print(teams);
for (int i =0; i< teams.length; i++){
var input = new CheckboxInputElement();
input.type = "checkbox";
input.id = "player";
input.onChange.listen((_) {
print("teamplayer ${input.checked}");
});
teamPlayer.append(input);
teamPlayer.appendText(teams[i]);
teamPlayer.appendHtml("<br>");
}