multi instance of a custom polymer-element and javascript dom manipulation - polymer

I have created a custom polymer component that is a chat component. When a message is posted, a fake answer is published. Nothing very complicated.
Besides, when I instantiate two instances of my component, when I click on the enter button to post a message, the instance of the textfield used to get the text is not the good one.
I don't know if it is a problem of my code or the way I code the component or the regular behavior with polymer.
Please, let me know what is going wrong.
Best regads,
here the code:
<link rel="import" href="../../../bower_components/polymer/polymer.html">
<!-- css import --> <!-- ... -->
<polymer-element name="chat-element">
<template>
<div class="chatview containerwindow" >
<div class="containertitle">
<span>CHAT VIEW</span>
</div>
<div class="chatcomponent">
<div id="messagecontainer" class="messagecontainer" >
</div>
<div class="footer">
<input type="text" class="inputtext" id="inputtextfield" />
<div class="insertchatbutton" id="insertchatbutton" >Enter</div>
</div>
</div>
</div>
</template>
<script>
Polymer('chat-element', {
myself: "",
inputextfiled: "",
insertchatbutton: "",
messagecontainer: "",
domReady: function() {
myself = this;
inputextfiled = this.$.inputtextfield;
inputextfiled.onkeyup = function(event) {
if (event.which == 13) {
myself.insertMessage(this);
}
};
insertchatbutton = this.$.insertchatbutton;
insertchatbutton.onclick = function() {
myself.insertMessage(inputextfiled);
};
messagecontainer = this.$.messagecontainer;
},
insertMessage : function (textview) {
var div = document.createElement('div');
div.classList.add('chatpushed');
var span = document.createElement('span');
span.innerHTML = textview.value;
div.appendChild(span);
messagecontainer.appendChild(div);
//scroll to the bottom
messagecontainer.scrollTop = messagecontainer.scrollHeight;
textview.value = "";
setTimeout(self.reply, 1000);
},
reply : function() {
var div = document.createElement('div');
div.classList.add('chatreceived');
var span = document.createElement('span');
span.innerHTML = "Message received";
div.appendChild(span);
messagecontainer.appendChild(div);
}
});
</script>

First off, here is a working version using more Polymer idioms:
http://jsbin.com/xokar/9/edit
Now, about some of the problems you are having. When you write
inputextfiled = this.$.inputtextfield
because you didn't use var you created a global variable. That means there is only one value of inputextfiled (sic) for the entire application.
You have to use this keyword to create and access instance variables, e.g., this.inputextfield.
You have a related problem here: setTimeout(self.reply, 1000);, because you instructed the timeout to call the self.reply function with window as this. You really want something like setTimeout(self.reply.bind(self)).
Here is some general information about this: http://www.quirksmode.org/js/this.html.

Related

Download the content of a div (save the div's appearance like an image) [duplicate]

I'm trying to capture a div into an image using html2canvas
I have read some similar question here like
How to upload a screenshot using html2canvas?
create screenshot of web page using html2canvas (unable to initialize properly)
I have tried the code
canvasRecord = $('#div').html2canvas();
dataURL = canvasRecord.toDataURL("image/png");
and the canvasRecord will be undefined after .html2canvas() called
and also this
$('#div').html2canvas({
onrendered: function (canvas) {
var img = canvas.toDataURL()
window.open(img);
}
});
browser gives some (48 to be exact) similar errors like:
GET http://html2canvas.appspot.com/?url=https%3A%2F%2Fmts1.googleapis.com%2Fvt%…%26z%3D12%26s%3DGalileo%26style%3Dapi%257Csmartmaps&callback=html2canvas_1 404 (Not Found)
BTW, I'm using v0.34 and I have added the reference file html2canvas.min.js and jquery.plugin.html2canvas.js
How can I convert the div into canvas in order to capture the image.
EDIT on 26/Mar/2013
I found Joel's example works.
But unfortunately when Google map embedded in my app, there will be errors.
<html>
<head>
<style type="text/css">
div#testdiv
{
height:200px;
width:200px;
background:#222;
}
div#map_canvas
{
height: 500px;
width: 800px;
position: absolute !important;
left: 500px;
top: 0;
}
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<script type="text/javascript" src="html2canvas.min.js"></script>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script language="javascript">
$(window).load(function(){
var mapOptions = {
backgroundColor: '#fff',
center: new google.maps.LatLng(1.355, 103.815),
overviewMapControl: true,
overviewMapControlOptions: { opened: false },
mapTypeControl: true,
mapTypeControlOptions: { position: google.maps.ControlPosition.TOP_LEFT, style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
panControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
zoomControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
streetViewControlOptions: { position: google.maps.ControlPosition.RIGHT_CENTER },
disableDoubleClickZoom: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
minZoom: 1,
zoom: 12
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
$('#load').click(function(){
html2canvas($('#testdiv'), {
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png")
window.open(img);
}
});
});
});
</script>
</head>
<body>
<div id="testdiv">
</div>
<div id="map_canvas"></div>
<input type="button" value="Save" id="load"/>
</body>
</html>
I ran into the same type of error you described, but mine was due to the dom not being completely ready to go. I tested with both jQuery pulling the div and also getElementById just to make sure there wasn't something strange with the jQuery selector. Below is an example that works in Chrome:
<html>
<head>
<style type="text/css">
div {
height: 50px;
width: 50px;
background-color: #2C7CC3;
}
</style>
<script type="text/javascript" src="html2canvas.js"></script>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script language="javascript">
$(document).ready(function() {
//var testdiv = document.getElementById("testdiv");
html2canvas($("#testdiv"), {
onrendered: function(canvas) {
// canvas is the final rendered <canvas> element
var myImage = canvas.toDataURL("image/png");
window.open(myImage);
}
});
});
</script>
</head>
<body>
<div id="testdiv">
</div>
</body>
</html>
If you just want to have screenshot of a div, you can do it like this
html2canvas($('#div'), {
onrendered: function(canvas) {
var img = canvas.toDataURL()
window.open(img);
}
});
you can try this code to capture a div When the div is very wide or offset relative to the screen
var div = $("#div")[0];
var rect = div.getBoundingClientRect();
var canvas = document.createElement("canvas");
canvas.width = rect.width;
canvas.height = rect.height;
var ctx = canvas.getContext("2d");
ctx.translate(-rect.left,-rect.top);
html2canvas(div, {
canvas:canvas,
height:rect.height,
width:rect.width,
onrendered: function(canvas) {
var image = canvas.toDataURL("image/png");
var pHtml = "<img src="+image+" />";
$("#parent").append(pHtml);
}
});
10 2022
This question is quite old, but if anyone looking for a clear solution to implement then here it is. This is using Pure JS with html2canvas and FileSaver
I have tested and it works fine.
Capture everything inside a div.
Step 1
Include the scripts in your footer. jQuery is not needed, These two are fine. If you already have these two in your file, watch out for the correct version. I know it's a little thing, but it is important.
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script>
Step 2
Basic div. The style attribute is optional. I am using it here to make it look presentable.
<div id="savethegirl" style="background-color:coral;color:white;padding:10px;width:200px;">
I am a Pretty girl 👩
</div>
<button onclick="myfunc()">Save the girl</button>
It should look like this
Step 3
Include this script
function myfunc(){
// if you are using a different 'id' in the div, make sure you replace it here.
var element = document.getElementById("savethegirl");
html2canvas(element).then(function(canvas) {
canvas.toBlob(function(blob) {
window.saveAs(blob, "Heres the Girl.png");
});
});
};
Step 4
Click the button and it should save the file.
Resources
CDN from: https://cdnjs.com/
This is from Carlos Delgado's article (https://ourcodeworld.com/articles/read/415/how-to-create-a-screenshot-of-your-website-with-javascript-using-html2canvas). I simplified it
If this answer is useful.
Hit that up arrow 🠉 It will help others to find it.
I don't know if the answer will be late, but I have used this form.
JS:
function getPDF() {
html2canvas(document.getElementById("toPDF"),{
onrendered:function(canvas){
var img=canvas.toDataURL("image/png");
var doc = new jsPDF('l', 'cm');
doc.addImage(img,'PNG',2,2);
doc.save('reporte.pdf');
}
});
}
HTML:
<div id="toPDF">
#your content...
</div>
<button id="getPDF" type="button" class="btn btn-info" onclick="getPDF()">
Download PDF
</button>
You can get the screenshot of a division and save it easily just using the below snippet. Here I'm used the entire body, you can choose the specific image/div elements just by putting the id/class names.
html2canvas(document.getElementsByClassName("image-div")[0], {
useCORS: true,
}).then(function (canvas) {
var imageURL = canvas.toDataURL("image/png");
let a = document.createElement("a");
a.href = imageURL;
a.download = imageURL;
a.click();
});
It can be easily done using html2canvas, try out the following,
try adding the div inside a html modal and call the model id using a jquery function. In the function you can specify the size (height, width) of the image to be displayed. Using modal is an easy way to capture a html div into an image in a button onclick.
for example have a look at the code sample,
`
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<div class="modal-body">
<p>Some text in the modal.</p>
`
paste the div, which you want to be displayed, inside the model. Hope it will help.
window.open didn't work for me... just a blank page rendered... but I was able to make the png appear on the page by replacing the src attribute of a pre-existing img element created as the target.
$("#btn_screenshot").click(function(){
element_to_png("container", "testhtmltocanvasimg");
});
function element_to_png(srcElementID, targetIMGid){
console.log("element_to_png called for element id " + srcElementID);
html2canvas($("#"+srcElementID)[0]).then( function (canvas) {
var myImage = canvas.toDataURL("image/png");
$("#"+targetIMGid).attr("src", myImage);
console.log("html2canvas completed. png rendered to " + targetIMGid);
});
}
<div id="testhtmltocanvasdiv" class="mt-3">
<img src="" id="testhtmltocanvasimg">
</div>
I can then right-click on the rendered png and "save as". May be just as easy to use the "snipping tool" to capture the element, but html2canvas is an certainly an interesting bit of code!
You should try this (test, works at least in Firefox):
html2canvas(document.body,{
onrendered:function(canvas){
document.body.appendChild(canvas);
}
});
Im running these lines of code to get the full browser screen (only the visible screen, not the hole site):
var w=window, d=document, e=d.documentElement, g=d.getElementsByTagName('body')[0];
var y=w.innerHeight||e.clientHeight||g.clientHeight;
html2canvas(document.body,{
height:y,
onrendered:function(canvas){
var img = canvas.toDataURL();
}
});
More explanations & options here: http://html2canvas.hertzen.com/#/documentation.html

$compile not triggering ng-click in angularjs

I am generating dynamic html element from angularjs controller.I have used $compile
to make ng-click work inside html element.But still it is not calling the function.
Here is my js
var accountApp = angular.module('accountApp', ['ngRoute']);
accountApp.config(['$compileProvider',function($compileProvider )
.controller('myController',function($scope,$compile)
{
var searchHTML = '<li><a href="javascript:void(0)" data-ng-
click="setMarkerToCenterA()">'+item.title+'</a></li>';
$compile(searchHTML)($scope);
$scope.setMarkerToCenterA = function() {
alert("this alert is not calling");
}
});
}]);
I have injected the dependencies also.Can anyone tell why ng-click is not calling function even though i am using $compile?
First you need an element where this li element will be located.
<div ng-controller="myController">
<ul id="list"></ul>
</div>
Then in your controller:
var element = angular.element("#list");
element.html($compile(html)($scope));
$scope.setMarkerToCenterA = function() {
alert("Here");
};
Probably you missed to parse the HTML string using angular.element(htmlString) which is then compiled.
var app = angular.module('stackoverflow', []);
app.controller('MainCtrl', function($scope, $compile, $sce) {
var searchHTML = 'hello';
var template = angular.element(searchHTML);
$compile(template)($scope);
angular.element(document.querySelector('#container')).append(template);
$scope.setMarkerToCenterA = function() {
alert("this alert is now calling");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.9/angular.min.js"></script>
<div ng-app="stackoverflow" ng-controller="MainCtrl">
<div id="container"></div>
</div>

React JS this.setState does nothing when updating content via a nested component

I am working on a simple react example that will alter the content of a header on the screen based on what a user enters in a text field. Here's the react code:
var GreeterForm = React.createClass({
onFormSubmit: function(e){
e.preventDefault();
var name = this.refs.name;
this.refs.name.value = '';
this.props.onNewName(name);
},
render: function(){
return(
<form onSubmit={this.onFormSubmit}>
<input type="text" ref="name"/>
<button>Set Name</button>
</form>
);
}
});
var Greeter = React.createClass({
//returns an object of the default properties to be used
//these are used if no properties are passed in
getDefaultProps: function(){
return {
name: 'React!',
message: "this is from a component!"
};
},
//maintains a state for the component. Maintains the state as an object
//this is a default method for react and we override it.
getInitialState: function(){
return {
name: this.props.name
};
},
handleNewName: function(name){
this.setState({
name: name
});
},
//renders the greeter react component
render: function() {
var name = this.state.name;
var message = this.props.message;
return (
<div>
<h1>Hello {name}!</h1>
<p>{message}</p>
<GreeterForm onNewName={this.handleNewName}/>
</div>
);
}
});
var firstName = "DefaultName";
var mess = "This is a message from react."
//note that name and message are passed in as properties
ReactDOM.render(<Greeter name={firstName} message={mess}/>, document.getElementById('app'));
You can see that GreeterForm is nested within Greeter and is supposed to alter the content of the h1 tag when the user submits.
However, the content of the h1 tag is not changing. I sprinkled alert(name.value) along the code to ensure the correct name from the input field was being passed around, and that all checked out.
What could it be? Is something wrong with my setState function?
Here's the HTML if needed:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.js"></script>
</head>
<body>
<div id="app">
</div>
<script type="text/babel" src="app.jsx"></script>
</body>
</html>
You are not sending value of input. you are sending whole html element
in onFormSubmit function change this line
var name = this.refs.name;
to
var name = this.refs.name.value;

Adding an angularJS directive based on a parameter value

TL;DR: Is there a way to dynamically set a directive based on a parameter value? Something similar to ng-class for setting css elements, but a way to set the directive based on the value in the scope. I would have the value in the scope so I could call:
<div class="data.directiveType"></div>
When
data.directiveType = "my-directive"
the div would become
<div class="my-directive"></div>
and myDirective would be invoked?
Detailed Question:
What I am trying to do is allow the user to add elements to the web application and I wanted the directive for each element to be added based on what the user clicks.
I have the following Directives:
app.directive("mySuperman", function(){
//directive logic
});
app.directive("myBatman", function(){
//directive logic
});
app.directive("myWonderWoman", function(){
//directive logic
});
I have the following controller
app.controller("ParentCtrl", function($scope){
$scope.superHeros = [];
var superman = {directiveType: "my-superman"};
var batman = {directiveType: "my-batman"};
var wonderWoman = {directiveType: "my-wonder-woman"}
$scope.addBatman = function()
{
var batmanInstance = {}
angular.copy(batman, batmanInstance);
$scope.superHeros.push(batmanInstance);
}
$scope.addSuperman = function()
{
var supermanInstance = {}
angular.copy(superman, supermanInstance);
$scope.superHeros.push(supermanInstance);
}
$scope.addWonderWoman = function()
{
var wonderwomanInstance = {}
angular.copy(wonderWoman, wonderwomanInstance);
$scope.superHeros.push(wonderwomanInstance);
}
});
In the index.html I have
<body ng-controller="ParentCtrl>
<a ng-click="addBatman()">Add Batman</a>
<a ng-click="addSuperman()">Add Superman</a>
<a ng-click="addWonderWoman()">Add WonderWoman</a>
<div ng-repeat="hero in superHeros">
<!-- The following doesn't work, but it is the functionality I am trying to achieve -->
<div class={{hero.directiveType}}></div>
<div>
</body>
The other way I thought of doing this was just using ng-include in the ng-repeat and adding the template url to the hero object instead of the directive type, but I was hoping there was a cleaner way that I could make better use of the data binding and not have to call ng-include just to call another directive.
You can create a directive that takes the directive to add as a parameter, adds it to the element and compiles it. Then use it like this:
<div ng-repeat="hero in superHeros">
<div add-directive="hero.directiveType"></div>
</div>
Here is a basic example:
app.directive('addDirective', function($parse, $compile) {
return {
compile: function compile(tElement, tAttrs) {
var directiveGetter = $parse(tAttrs.addDirective);
return function postLink(scope, element) {
element.removeAttr('add-directive');
var directive = directiveGetter(scope);
element.attr(directive, '');
$compile(element)(scope);
};
}
};
});
Demo: http://plnkr.co/edit/N4WMe8IEg3LVxYkdjgAu?p=preview

Angular - append html through different frames with one module per frame

My code have the main windonw and one iframe and each one with your module. A button in main window fires click event that should append html into iframe, the new html when appended into that should apply interceptors and directives properly, but it doesn't work!
Angular javascript:
angular.module('module1',[]).controller('Controller1', function ($scope) {
$scope.get = function(){
$http.jsonp("some_url_here").success(function(html){
$scope.content = html;
});
}
}).directive('click', function($compile) {
return {
link: function link(scope, element, attrs) {
element.bind('click',function(){
var unbind = scope.$watch(scope.content, function() {
var div=document.getElementById("frame").contentWindow.angular.element("divId");
div.append($compile(scope.content)(div.scope()));
unbind();
});
});
}
}
});
angular.module('module2',[]).directive('a', function() {
return {
restrict:'E',
link: function(scope, element, attrs) {
console.log('ping!');
console.log(attrs.href);
}
};
});
Html code:
<html ng-app="modile1">
<div ng-controller="Controller1">
<button type="button", ng-click="get('any_value')", click:""/> Load frame
</div>
<iframe id="frame" src="/please/ignore/this">
<!-- considere the html as appended from iframe-src and contains ng-app="module2" -->
<html ng-app="module2">
<div id="divId">
<!-- code should be inject here -->
</div>
</html>
</iframe>
</html>
Please, considere that angularjs, jquery if applicable, modules-declaration as well as headers are loaded properly.
I'd like to load the html content from main-frame/window into iframe and run interceptors and directives properly. Is it possible? If yes, how can I do it?
Thanks for advancing!
I've tried this code and it seems work fine! I found it here: http://www.snip2code.com/Snippet/50430/Angular-Bootstrap
var $rootElement = angular.element(document.getElementById("frame").contentWindow.document);
var modules = [
'ng',
'module2',
function($provide) {
$provide.value('$rootElement', $rootElement)
}
];
var $injector = angular.injector(modules);
var $compile = $injector.get('$compile');
$rootElement.find("div#divId").append(scope.content);
var compositeLinkFn = $compile($rootElement);
var $rootScope = $injector.get('$rootScope');
compositeLinkFn($rootScope);
$rootScope.$apply();