JavaScript "this" not working for HTML element - javascript

I want to display information in div with img element which i'm accessing to database through php. I am associating onmouseover event with each element and passing this and some parameters as arguments but as I mouse over on image, div show at top left of browser and does not show beside image.
I have also tried with remove this and the result is same old one.
code for image element
$row = mysqli_fetch_array($result);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$image = $row['image'];
$phone = $row['phone'];
$email = $row['email'];
$realtorData = $firstname.'|'.$lastname.'|'.$phone.'|'.$email.'|';
echo "<img src='/../../Realtors/$image'onmouseover='showRealtorInfo(this,\"".$realtorData."\" );' onmouseout='hideRealtorInfo();'>";
javaScript code
function showRealtorInfo(element, realtorInfo)
{
var realtorArray = realtorInfo.split('|');
var firstname = realtorArray[0];
var lastname = realtorArray[1];
var phone = realtorArray[2];
var email = realtorArray[3];
var realtorInfoDiv = document.getElementById('realtorinfo');
var myHTML = "<p><b>" + firstname + " " + lastname + "</b><br /><br />";
myHTML += "Phone: " + phone + "<br />";
myHTML += "Email: " + email + "<br />";
realtorInfoDiv.innerHTML = myHTML;
x = element.offsetLeft;
y = element.offsetTop;
//alert(x);
realtorInfoDiv.style.left = y + 100;
realtorInfoDiv.style.top = x + 550;
realtorInfoDiv.style.visibility = 'visible';
}
css code for div element
#realtorinfo{
position: absolute;
left: 10px;
top: 10px;
width: 200px;
height: 150px;
padding: 5px;
background-color: yellow;
visibility: hidden;
float: left;
}

You have not mentioned "px" in the follow LOC.
realtorInfoDiv.style.left = y + 100;
realtorInfoDiv.style.top = x + 550;
This should work:
realtorInfoDiv.style.left = y + 100 + "px";
realtorInfoDiv.style.top = x + 550 + "px";

Related

Trouble with script-generated dynamic html element

I developing comment section for my HTMl page. I place it in div container in body section in my page, like that:
<body>
...
<div id='commentsTree'></div>
...
</body>
Commment section generated by script, here it is
function createCommentsTree(commentsData) {
resultHTML = "";
let commentsArray = JSON.parse(commentsData);
//let result = "";
resultHTML = resultHTML + "<ul id='myUL'>";
commentsArray.forEach(element => {
if (element.hasOwnProperty("subordinates")){
resultHTML = resultHTML + "<li>" +
"<span class='caret'></span><textarea class='textFieldRoot'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>";
createCommentsTreeHyerarchycally(element);
resultHTML = resultHTML + "</li>";
}
else{
resultHTML = resultHTML + "<li>" +
"<textarea class='textField'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>" +
"</li>";
}
});
resultHTML = resultHTML + "</ul>";
return resultHTML;
}
function createCommentsTreeHyerarchycally(source) {
resultHTML = resultHTML + "<ul class='nested'>";
source.subordinates.forEach(element => {
if (element.hasOwnProperty("subordinates")){
resultHTML = resultHTML + "<li>" +
"<span class='caret'></span><textarea class='textFieldRoot'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>";
createCommentsTreeHyerarchycally(element);
resultHTML = resultHTML + "</li>";
}
else{
resultHTML = resultHTML + "<li>" +
"<textarea class='textField'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>" +
"</li>";
}
})
resultHTML = resultHTML + "</ul>";
}
in result i have hyerarchycally comments tree, you can see it on example here
https://jsfiddle.net/Obliterator/wogurs6L/, or, on picture "comment section" added below.
On picture you can see "caret" symbol, looks like black small arrow near textareas, i mark it on picture. When i click it, comment line must unfold, and show subordinate comment lines. You can try it in example here https://jsfiddle.net/Obliterator/wogurs6L/, in this example it works totally correct. But, in my web page, when i click on "caret" symbol, nohing happens, comment line do not unfold. And this is a problem.
For unfold by clicking "caret" symbol i make this script and css:
script:
var toggler = document.getElementsByClassName("caret");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
css:
/* Remove default bullets */
ul, #myUL {
list-style-type: none;
}
.textFieldRoot {
position: relative;
left: 15px;
width: 100%;
}
.textField {
position: relative;
width: 100%;
}
/* Remove margins and padding from the parent ul */
#myUL {
margin: 0;
padding: 0;
}
/* Style the caret/arrow */
.caret {
cursor: pointer;
user-select: none; /* Prevent text selection */
position: absolute;
}
/* Create the caret/arrow with a unicode, and style it */
.caret::before {
content: "\25B6";
color: black;
display: inline-block;
margin-right: 6px;
vertical-align: top;
}
/* Rotate the caret/arrow icon when clicked on (using JavaScript) */
.caret-down::before {
transform: rotate(90deg);
}
/* Hide the nested list */
.nested {
display: none;
}
/* Show the nested list when the user clicks on the caret/arrow (with JavaScript) */
.active {
display: block;
}
i add css and script in my page, for which i trying add comment section, that way (treeListScript.js and treeListStyle.css):
<head>
...
<script type="text/javascript" src="http://localhost/testapp/lib/others/treeList/treeListScript.js"></script>
<link rel="stylesheet" href="http://localhost/testapp/lib/others/treeList/treeListStyle.css">
...
</head>
<body>
...
<div id='commentsTree'></div>
...
</body>
i create my web page this way:
var windowTask = window.open("http://localhost/testapp/site/windows/formTask.html", "taskForm");
windowTask.onload = function(){
windowTask.document.getElementById("formTitle").innerText = "Task " + selectedRow.taskID;
windowTask.document.getElementById("taskID").value = selectedRow.taskID;
windowTask.document.getElementById("title").value = selectedRow.title;
windowTask.document.getElementById("status").value = selectedRow.status;
windowTask.document.getElementById("creator").value = selectedRow.creator;
windowTask.document.getElementById("responsible").value = selectedRow.responsible;
windowTask.document.getElementById("description").value = selectedRow.description;
windowTask.document.getElementById("dateCreation").value = selectedRow.dateCreation;
windowTask.document.getElementById("dateStart").value = selectedRow.dateStart;
windowTask.document.getElementById("dateFinish").value = selectedRow.dateFinish;
var comments = getCommentsTree(selectedRow.taskID, 'task');
windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments);
line windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments); creates comment section.
So, what i am doing wrong, what i mus do for my unfold fucntional works correct on my web page? If something unclear, ask, i try explain.
I solve problem by myself. Reason is i just incorrect add event handler to the .caretelements, i add it as script in head section, but i need to add it after i generate comment section, this way:
//creating new HTML page +++
var windowTask = window.open("http://localhost/testapp/site/windows/formTask.html", "taskForm");
windowTask.onload = function(){
windowTask.document.getElementById("formTitle").innerText = "Task " + selectedRow.taskID;
windowTask.document.getElementById("taskID").value = selectedRow.taskID;
windowTask.document.getElementById("title").value = selectedRow.title;
windowTask.document.getElementById("status").value = selectedRow.status;
windowTask.document.getElementById("creator").value = selectedRow.creator;
windowTask.document.getElementById("responsible").value = selectedRow.responsible;
windowTask.document.getElementById("description").value = selectedRow.description;
windowTask.document.getElementById("dateCreation").value = selectedRow.dateCreation;
windowTask.document.getElementById("dateStart").value = selectedRow.dateStart;
windowTask.document.getElementById("dateFinish").value = selectedRow.dateFinish;
//creating new HTML page ---
//creating comment section +++
var comments = getCommentsTree(selectedRow.taskID, 'task');
windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments);
//creating comment section ---
//adding event handler +++
var toggler = windowTask.document.getElementsByClassName("caret");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
//adding event handler ---
now everything works fine. If anyone spend some time for my question, thx.

Undefined variables in html templates for MailApp

I am trying to send an HTML email using MailApp.
This is the table where I will pull the data from:
After reading the documentations and posts on SO, I am still unable to pin point why the email sent out is showing undefined in the variables part.
Would appreciate if someone can point me to the right direction.
These are my codes:
sendHtmlEmail.gs
function sendEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lastRow = ss.getLastRow();
var quotaLeft = MailApp.getRemainingDailyQuota();
if((lastRow-1) > quotaLeft){
Browser.msgBox("You have " + quotaLeft + " email quota left and you're trying to send " + (lastRow-1) + " emails. Emails were not sent.")
} else {
for (var row = 2; row <= lastRow; row++){
var currentEmail = ss.getRange(row, 4).getValue();
var currentContact = ss.getRange(row, 3).getValue();
var currentNewSize = ss.getRange(row,8).getValue();
var currentSub = ss.getRange(row, 9).getValue();
var returnData = [currentContact, currentNewSize, currentSub];
var html = HtmlService.createTemplateFromFile('htmlTemplate');
html.data = returnData;
var template = html.evaluate().getContent();
var subjectLine = "Important notice";
MailApp.sendEmail({to: currentEmail, subject: subjectLine, htmlBody: template});
} //close for loop
Browser.msgBox("You have successfully sent " + (lastRow-1) + " emails.")
} //close else statement
}
htmlTemplate.html
<!DOCTYPE html><html><head><base target="_top"></head><body style="text-align: center;font-family: Arial;">
<div id="center" style="width:300px;border: 2px dotted grey;background:#ececec;margin:25px;margin-left:auto;
margin-right:auto;padding:15px;"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/Simple_Alert.svg/600px-Simple_Alert.svg.png"
width="180" style="margin:10px 0px"><br /><div style=" border: 2px dotted grey;background:white;margin-right:auto; margin-left:auto;
padding:10px;"><h2>Alert</h2><h3>Important Notice <br /><br />
+ <?= data.currentContact ?> + '<br />' + <?= data.currentNewSize ?> + '<br />' + <?= data.currentSub ?> + '<br /></h3></div></body></html>'
I know that it is something to do with the htmlTemplate data.currentNewSize etc, but after tweaking my codes they are still showing undefined as shown in the image.
You are using an array in the method while the template is expecting an object.
Replace
var returnData = [currentContact, currentNewSize, currentSub];
with
var returnData = {currentContact: currentContact, currentNewSize: currentNewSize, currentSub: currentSub}
The issue lies in the html code. As I have declared the array in sendHtmlEmail.gs, I did not call it correctly in my htmlTemplate.html.
In this line:
var returnData = [currentContact, currentNewSize, currentSub];
currentContact is in position 0, currentNewSize is in position 1 and so forth.
In the htmlTemplate.html, I need to replace this line:
+ <?= data.currentContact ?> + '<br />' + <?= data.currentNewSize ?> + '<br />' + <?= data.currentSub ?> + '<br /></h3></div></body></html>'
with this:
+ <?= returnData[0];?> + '<br />' + <?= returnData[1];?> + '<br />' + <?= returnData[2];?> + '<br /></h3></div></body></html>'

show progress when click button Dynamics CRM 365

I have a ribbon button to execute custom workflow. this action a setup from JavaScript and it worked perfectly. In this case I wanna show progress loading when after click or during custom workflow execution.
I just followed the tutorial HERE. this my javascript function code:
function showLoadingMessage() {
try{
tdAreas.style.display = 'none';
var newdiv = document.createElement('div');
newdiv.setAttribute('id', "msgDiv");
newdiv.valign = "middle";
newdiv.align = "center";
var divInnerHTML = "<table height='100%' width='100%' style='cursor:wait'>";
divInnerHTML += "<tr>";
divInnerHTML += "<td valign='middle' align='center'>";
divInnerHTML += "<img alt='' src='/_imgs/AdvFind/progress.gif'/>";
divInnerHTML += "<div/><b>Working…</b>";
divInnerHTML += "</td></tr></table>";
newdiv.innerHTML = divInnerHTML;
newdiv.style.background = '#FFFFFF';
newdiv.style.fontSize = "15px";
newdiv.style.zIndex = "1010";
newdiv.style.width = document.body.clientWidth;
newdiv.style.height = document.body.clientHeight;
newdiv.style.position = 'absolute';
document.body.insertBefore(newdiv, document.body.firstChild);
document.all.msgDiv.style.visibility = 'visible';
}
catch(ex){
alert(ex.message);
}
}
and this one is to hide progress:
function hideLoadingMessage(){
document.all.msgDiv.style.visibility = 'hidden';
}
this is the function that I called in my ribbon button action for testing loading progress work or not:
function ribbonButton()
{
var guid = Xrm.Page.data.entity.getId();
if (guid != null)
{
showLoadingMessage(); //show progress
/*var workflowId = '04E84379-87E4-E711-814E-000C294D2FF8';
var workflowName = 'CloneReward';
ExecuteWorkflow(workflowId, workflowName, function ()
{
RefreshForm();
});*/
//hideLoadingMessage(); //hide progress
}
}
when I pressed the button I get the following error message:
Need any suggestions. Thanks.
There is new nice client API for exact this feature: https://learn.microsoft.com/en-us/dynamics365/customer-engagement/developer/clientapi/reference/xrm-utility/showprogressindicator
Here is example on how it looks in work: http://www.itaintboring.com/dynamics-crm/dynamics-365-v9-progress-indicator-api/
The only downside is that it's only applicable to Dynamics version 9.
just tried this THIS tutorial and it will fix the problem above.
show loading progress:
function _buildLoadingDiv(_entityName) {
var loadingDiv = "<div id='divLoading'style='width: 100%; height: 100%; display: block; position: fixed; top:0px; background:rgba(255,255,255,0.5);'><table style='width: 100%; height: 100%;'><tr><td align='center' style='vertical-align: middle;'>";
loadingDiv += "<img id='loading' alt='' src='/_imgs/AdvFind/progress.gif'/><br/>";
loadingDiv += "<label id='lblStatus'>Loading... " + _entityName + " Execute Workflow</label>";
loadingDiv += "</td></tr></table></div>";
$($('body', window.parent.document)).append(loadingDiv);
}
hide loading progress:
function _removeLoading() {
$($('body', window.parent.document)).find("#divLoading").remove();
}

Moving Javascript variables into Html Table

i found this guide to create a stock ticker.
I tried to change it into an html table, but i'm stuck.
So, i created the table, but i have big problems to divide each variable.
What i want to accomplish is a table with this columns order:
Symbol: CompName
Price: Price
Change: PriceIcon + ChnageInPrice
%: PercentChnageInPrice
What i've accomplished for now it's just this, all the content in one column (because of the variable StockTickerHTML i guess)
Full Code Link
Can you please help me?
var CNames = "^FTSE,FTSEMIB.MI,^IXIC,^N225,^HSI,EURUSD=X";
var flickerAPI = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + CNames + "%22)&env=store://datatables.org/alltableswithkeys";
var StockTickerHTML = "";
var StockTickerXML = $.get(flickerAPI, function(xml) {
$(xml).find("quote").each(function () {
Symbol = $(this).attr("symbol");
$(this).find("Name").each(function () {
CompName = $(this).text();
});
$(this).find("LastTradePriceOnly").each(function () {
Price = $(this).text();
});
$(this).find("Change").each(function () {
ChnageInPrice = $(this).text();
});
$(this).find("PercentChange").each(function () {
PercentChnageInPrice = $(this).text();
});
var PriceClass = "GreenText", PriceIcon="up_green";
if(parseFloat(ChnageInPrice) < 0) { PriceClass = "RedText"; PriceIcon="down_red"; }
StockTickerHTML = StockTickerHTML + "<span class='" + PriceClass + "'>";
StockTickerHTML = StockTickerHTML + "<span class='quote'>" + CompName + " </span> ";
StockTickerHTML = StockTickerHTML + parseFloat(Price).toFixed(2) + " ";
StockTickerHTML = StockTickerHTML + "<span class='" + PriceIcon + "'></span>" + parseFloat(Math.abs(ChnageInPrice)).toFixed(2) + " (";
StockTickerHTML = StockTickerHTML + parseFloat( Math.abs(PercentChnageInPrice.split('%')[0])).toFixed(2) + "%)</span> </br>";
});
$("#dvStockTicker").html(StockTickerHTML);
$("#dvStockTicker").jStockTicker({interval: 30, speed: 2});
});
}
One solution could be this :
(see comments in code)
$(window).load(function() {
StockPriceTicker();
setInterval(function() {
StockPriceTicker();
}, 2 * 1000); // <------ we refresh each 2 seconds
});
// we get the table's body where
// the lines will be inserted.
var $body = $('table tbody');
/*
this will be the cache of
our lines, once they are prepared / transformed
as your need, we will join and insert them
in the body of our table.
*/
var Lines = [];
/*
We define a function in charge of creating the HTML
of each row of hour table, and then push them
in the array defined above "Lines".
*/
var addLine = function(symbol, price, change, percent) {
Lines.push('<tr>' +
'<td class="symbol" >' + symbol + '</td>' +
'<td class="price" >' + price + '</td>' +
'<td class="change" >' + change + '</td>' +
'<td class="percent">' + percent + '</td>' +
'</tr>');
};
// this is your function to get data
function StockPriceTicker() {
var Symbol = "",
CompName = "",
Price = "",
ChnageInPrice = "",
PercentChnageInPrice = "";
var CNames = "^FTSE,FTSEMIB.MI,^IXIC,^N225,^HSI,EURUSD=X";
var flickerAPI = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + CNames + "%22)&env=store://datatables.org/alltableswithkeys";
var StockTickerXML = $.get(flickerAPI, function(xml) {
$(xml).find("quote").each(function() {
Symbol = $(this).attr("symbol");
$(this).find("Name").each(function() {
CompName = $(this).text();
});
$(this).find("LastTradePriceOnly").each(function() {
Price = $(this).text();
});
$(this).find("Change").each(function() {
ChnageInPrice = $(this).text();
});
$(this).find("PercentChange").each(function() {
PercentChnageInPrice = $(this).text();
});
var PriceClass = "GreenText",
PriceIcon = "up_green";
if (parseFloat(ChnageInPrice) < 0) {
PriceClass = "RedText";
PriceIcon = "down_red";
}
/*
We create the html to be inserted on each xml loop.
- First : prepare and transform as you need
- Last : use the function we define above "addLine";
*/
var htmlSymbol,
htmlPrice,
htmlChange,
htmlPercent;
htmlSymbol = "<span class='" + PriceClass + "'>";
htmlSymbol = htmlSymbol + "<span class='quote'>" + CompName + " </span></span>";
htmlPrice = parseFloat(Price).toFixed(2) + " ";
htmlChange = parseFloat(Math.abs(ChnageInPrice)).toFixed(2) + "<span class='" + PriceIcon + "'></span>";
htmlPercent = parseFloat(Math.abs(PercentChnageInPrice.split('%')[0])).toFixed(2) + "%";
// We use here the function defined above.
addLine(htmlSymbol, htmlPrice, htmlChange, htmlPercent);
});
/*
Once the loop of reading the XML
end, we have pushed all html in the array "Lines".
So now we delete the content of our table's body, and
we fill it with all the lines joined.
*/
$body.empty().html(Lines.join(''));
// we reset the content of Lines for the next interval
Lines = [];
});
}
.GreenText {
color: Green;
}
.RedText {
color: Red;
}
.up_green {
background: url(http://www.codescratcher.com/wp-content/uploads/2014/11/up.gif) no-repeat left center;
padding-left: 10px;
margin-right: 5px;
margin-left: 5px;
}
.down_red {
background: url(http://www.codescratcher.com/wp-content/uploads/2014/11/down.gif) no-repeat left center;
padding-left: 10px;
margin-right: 5px;
margin-left: 5px;
}
table {
border: solid;
border-color: #666;
}
td {
padding: 3px;
}
.symbol {
border: solid 3px #DDD;
}
.price {
border: solid 3px aqua;
}
.change {
border: solid 3px yellow;
}
.percent {
border: solid 3px purple;
}
td.price,
td.change,
td.percent {
text-align: right;
}
tbody tr:nth-child(odd){
background-color:#EEF;
}
tbody tr:nth-child(even){
background-color:#AAA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table>
<thead>
<tr>
<th class='symbol'>Symbol</th>
<th class='price'>Price</th>
<th class='change'>Change</th>
<th class='percent'>%</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

Styling Divs with Javascript Vars

I'm doing a little experiment trying to randomly place images inside a div using a javascript loop. I've been having some trouble with it.
Here's what I have (simplified):
for(var i = 0; i < 10; i++)
{
var top = random(-20, 20);
var left = random(-20, 20);
document.write(
<div class="one" style="\"left:" + left + ";\"">
<img src="hein.png"/>
</div>
);
}
The goal being to generate some top and left values, and every itteration display a new image with these generated values. I know it's a syntax error with the style="". But nothing I've tried has worked
How can I get this working.
You meed to wrap the whole of the document.write output in quotes, like this:
document.write('<div class="one" style="left:"' + left + ';"><img src="hein.png"/></div>');
You should first consider using a JavaScript library like jQuery. This will simplify your work.
Let's say you have this markup
<div id="image-container">
</div>
Include jQuery in you markup
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
From JavaScript you would do this, after you've included jQuery in your markup
for(var i = 0; i < 10; i++) {
var top = random(-20, 20);
var left = random(-20, 20);
$('#image-container').append('<img src="hein.png" style="position: absolute; top: '+top+'; left : '+left +';" />');
}
You forgot the quotes in document.write and you are escaping wrong characters inside of it
document.write(
"<div class=\"one\" style=\"left:" + left + ";\">
<img src=\"hein.png\"/>
</div>"
);
You have forgotten to quote the string in the document.write call. Also you forgot the unit on the measurement.
for(var i = 0; i < 10; i++) {
var top = random(-20, 20);
var left = random(-20, 20);
document.write(
'<div class="one" style="left:' + left + 'px;top:' + top + 'px">' +
'<img src="hein.png"/>' +
'</div>'
);
}
Using PHP Instead:
<?php
// Middle coords of my div
$top = 200;
$left = 350;
for($i = 0; $i < 20; $i += 1)
{
$tran = rand(-130,170);
$lran = rand(-300,270);
// Fix line breaks
$top = $top - 49;
echo '<div style="position:relative;
display: block;
height: 49px;
width:49px;
left:' . ($left + $lran) . 'px;
top:' . ($top + $tran) . 'px;
">' . '<img src="img.png"/>' . '</div>';
}
?>
Awesome! Thanks for the help with the string syntax!

Categories

Resources