How to replace innerHTML with jQuery? - javascript

I have written the code below but now I have to write this with jQuery because of security reasons. I have never done something with jQuery before and I really don't know, how to write this.
I shouldn't mix the HTML with JS and should use createElement and stuff like that.
var demoName1 = "Peter Stone";
function showMessage() {
var newMsg = '<div id="messageBoxSend">' +
'<div class="nameSend">' + demoName1 + '</div>' +
'<div class="text">' +
' <div id="FscToolPaneNoseSend">' +
'</div></div>' +
document.getElementById('inputText').value;
var a = new Date();
var b = a.getHours();
var c = a.getMinutes();
if (c < 10) {
c = "0" + c;
}
var time = b + ':' + c;
newMsg += '<div class="time">' + time + '</div>' +
' </div></div><br>';
...
}

You will try this code
$('class or id').html('');
$('class or id').html(newMsg);

jQuery is a library for JavaScript, so yes, if you consider JavaScript to be insecure, then jQuery is, as well. Also, jQuery makes AJAX easier, but it doesn't prove that Jquery is secure than javascript.

It would be something like the below. You should probably look into the jQuery docs https://jquery.com/
var demoName1 = "Peter Stone";
function showMessage() {
var input = $('#inputText').val();
$('.nameSend').html(demoName1 + input);
var a = new Date();
var b = a.getHours();
var c = a.getMinutes();
if (c < 10) {
c = "0" + c;
}
var time = b + ':' + c;
$('#messageBoxSend').append(time);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="inputText">
<div id="messageBoxSend">
<div class="nameSend"></div>
</div>
<div class=""></div>
<button onclick="showMessage();">Click me!</button>
After reading the comments and your question, I realized that the security concern should be answered. It is recommended to sanitize the HTML before using innerHTML().
You can read more on creating DOM elements and using innerHTML() safely here https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Safely_inserting_external_content_into_a_page

Related

Current Alternative To .fontcolor() method in Javascript

I was given this task with some existing code to change the string color of each of three selector.value(s) that is output onto an input element to three different colors. The code boils the three selectors into a single output variable. Without destroying the code, I cannot figure out how to select each individual variables prior to condensing them.
If I could use the fontcolor() method, my life would be great but it's 2018 and I can't. Is there any way you can think of to solve this issue?To clarify, I need to alter the colors of the strings that belong to output(red), select1.value(blue) and select2.value(black.
Most of the action for this is happening in the parseOutput() function but I'm just stuck and don't think it's possible without rewriting the entire program.
function updateSelector(result){
var options = result.options;
var elementId = "select" + result.element;
var logger = document.getElementById('logger');
var selector = document.getElementById(elementId);
//logger.innerHTML = JSON.stringify(elementId);
selector.innerHTML = options;
selector.disabled = false;
}
google.script.run.withSuccessHandler(updateSelector).processOptions(0);
plate();
function resetAll(){
for (var i = 0;i<3;i++){
var selector = document.getElementById('select' + i);
selector.disabled = true;
selector.innerHTML = "";
}
google.script.run.withSuccessHandler(updateSelector).processOptions(0);
}
function finalSelection(){
var output = document.getElementById('out');
//output.focus();
output.select();
}
function plate(){
var plate = document.getElementById('plate');
plate.innerHTML = atob('Q3JhZnRlZCBieTogWmFjaGFyeSBTdGFjaG93aWFr');
}
//Adds the location as initial output, followed by divider, application, and issue if select1 is selected
//else statement added so if select0 is [Costco Website Name], to ommit the " - "
function parseOutput(){
var output = "";
if (select1.value.length > 0 && select0.value !== "[Costco Website Name]"){
output = output + ' - ' + select1.value + ' // ' + select2.value;
} else{
output = output + select1.value + ' // ' + select2.value;
}
out.value=output.trim();
}
And this is the Div that displays the output:
<div class="wide"><p><input class="wide" type="readonly" id="out" onfocus="this.select();"></p></div>
A modern replacement for fontcolor would use a span and a style (or class), e.g.:
function modernFontColor(str, color) {
return '<span style="color: ' + color + '">' + str + '</span>';
}
or
function modernFontClass(str, cls) {
return '<span class="' + cls + '">' + str + '</span>';
}
...where the class defines the styling.

How would I wrap a javascript variable within a span or bold tag?

I've been given some JavaScript that creates a digital clock to go onto a webpage. This is working perfectly, however I'm trying amend it to wrap the am/pm suffix (or diem in this code) in span or bold tags so that I can style it differently to the rest of the time in the CSS.
I'm sure this would be really simple for someone that knows what they're doing but I'm really struggling. Any help would be appreciated, the JavaScript is below:
function renderTime() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
setTimeout('renderTime()',1000);
if (h == 0) {
h = 12;
} else if (h > 12) {
h = h - 12;
diem="PM";
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockDisplay');
myClock.textContent = h + ":" + m + " " + diem;
myClock.innerText = h + ":" + m + " " + diem;
var diem = document.createElement('span');
}
renderTime();
You have a few options:
Use innerHTML instead of innerText. That allows you to insert HTML tags into the string:
myClock.innerHTML = h + ":" + m + " <span>" + diem + "</span>;
Use appendChild and leave out the diem at the end of the innerText:
myClock.innerText = h + ":" + m + " ";
var diemSpan = document.createElement('span');
diemSpan.innerText = diem;
myClock.appendChild(diemSpan);
Finally, you could put a clockDisplay and a diem span within your markup and access them appropriately:
Markup:
<div id="clockDisplay">
<span id="clockDisplay-time"></span>
<span id="clockDisplay-suffix"></span>
</div>
Script:
document.getElementById("clockDisplay-time").innerText = h + ":" + m;
document.getElementById("clockDisplay-suffix").innerText = diem;
Try this:
var myClock = document.getElementById('clockDisplay');
var suffix = document.createElement('span');
suffix.innerText = diem;
myClock.innerText = h + ":" + m + " ";
myClock.append(suffix);
Or, if you want to be more efficient (pure DOM manipulation):
var myClock = document.getElementById('clockDisplay');
var suffix = document.createElement('span');
suffix.append(document.createTextNode(diem));
myClock.append(document.createTextNode(h + ":" + m + " "));
myClock.append(suffix);
Here's a JSfiddle for you. It should work the way you wanted.
A solution is to create a different span for the time and your "diem", like this:
HTML:
<p><span id="time"><!-- time will go here --></span><span id="diem"><!-- "diem" will go here --></span></p>
Then access them separately. You can style them differently too in CSS, like this:
CSS:
span#diem {
font-weight: bold;
// your styles
}
JS:
window.onload = function() {
renderTime();
}
function renderTime() {
// Insert time calculations here
var time_span = document.getElementById('time');
time_span.innerText = h + ":" + m;
var diem_span = document.getElementById("diem");
diem_span.innerText = " " + diem;
}
See the Fiddle for the complete code in renderTime().

What is a better way to write HTML than document.write in JavaScript?

I found working JavaScript code to feed into a jQuery mobile app here and made some minor modifications to it.
As I am very new to JavaScript - currently in the beginning of the JavaScript course at codeacademy.com - I didn't realize that document.write is not the best way to output/build your HTML.
When the .js file is loaded it's like a blank page which I believe is due to document.write. When I refresh, the RSS feed displays correctly. I'm having a very hard time figuring out what code I need to use to replace the document.write portions.
I've seen document.getElementById('div1').innerHTML='test' but not quite sure how to use this to replace document.write in the code below.
If someone would provide the alternative code for document.write in one of the sections below before the JSON code I would be extremely grateful.
/* configuration */
var maxLength = 10;
/* writing HTML */
document.write(
/* page begins */
'<div id="news" data-role="page" data-theme="a" data-title="NEWS">' +
' <div data-role="content">' +
' <ul data-role="listview" data-filter="true" id="dynamiclist" data-inset="true">'
);
for (var i=1; i<=maxLength; i++){
document.write(
'<li id="list' + i + '"> </li>'
);
}
document.write(
' </ul>' +
' </div>' +
'</div>'
);
for (i=1; i<=maxLength; i++){
document.write(
'<div data-role="page" id="article' + i + '">' +
' <div data-role="content">' +
' <h3 id="articleHeader' + i + '"> </h3>' +
' <div id="articleContent' + i + '" class="articleContent">' +
' <p id="articleDate' + i + '" class="articleDate"></p></div>' +
' <div data-role="controlgroup" data-type="horizontal">' +
' News' +
' <a href="#article' + String(i-1) + '" data-role="button" data-icon="arrow-l"' +
' data-inline="true" class="prevButton">Prev</a>' +
' <a href="#article' + String(i+1) + '" data-role="button" data-icon="arrow-r"' +
' data-inline="true" class="nextButton" data-iconpos="right">Next</a>' +
' </div>' +
' </div>' +
'</div>'
);
}
/* JSONP */
$(function(){
getOnlineFeed('http://rss.cnn.com/rss/money_news_economy.rss');
});
/* functions */
var getOnlineFeed = function(url) {
var script = document.createElement('script');
script.setAttribute('src', 'http://ajax.googleapis.com/ajax/services/feed/load?callback=listEntries&hl=ja&output=json-in-script&q='
+ encodeURIComponent(url)
+ '&v=1.0&num=' + maxLength);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
var getOfflineFeed = function(url) {
var script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
var listEntries = function(json) {
if (!json.responseData.feed.entries) return false;
$('#widgetTitle').text(json.responseData.feed.title);
var articleLength =json.responseData.feed.entries.length;
articleLength = (articleLength > maxLength) ? maxLength : articleLength;
for (var i = 1; i <= articleLength ; i++) {
var entry = json.responseData.feed.entries[i-1];
$('#link' + i).text(entry.title);
$('#articleDate' + i).text(entry.pubdate);
$('#articleHeader' + i).text(entry.title);
$('#openButton' + i).attr('href', entry.link);
$('#articleContent' + i).append(entry.content);
}
$('#article1 .prevButton').remove();
$('#article' + articleLength + ' .nextButton').remove();
if (articleLength < maxLength) {
for (i = articleLength + 1; i <= maxLength; i++) {
$('#list' + i).remove();
$('#article' + i).remove();
}
}
};
$('#PageRefresh').click(function() {
location.reload();
});
Edit: I did not read the question carefully enough the first time - I now see that you're already using jQuery, but not before you do your DOM manipulation. So the rest of the answer stands - use .html() and manipulate the DOM only after the document is ready.
Here's my suggestion. Full disclaimer: this is not the only way to do it nor is it necessarily the "best" way to do it. I daresay it would be the most common way to do it, however.
Use jQuery - it will make your life so much easier. http://jquery.com
Make sure you do your DOM (Document Object Model) manipulation (inserting HTML elements to your document is a type of DOM manipulation, although I'm not sure that document.write() is) after it is ready. jQuery provides a nice method to do just this. http://api.jquery.com/ready/
$(function() {
// Handler for .ready() called
});
Use the .html() function within jQuery to write to your <body> element or a <div> element that you write directly in your HTML file. http://api.jquery.com/html/
HTML
<html>
<body>
<div id="content"></div>
</body>
</html>
jQuery
var page = "This should have the HTML you want to insert";
$(function() {
$("#content").html(page);
});

adding a class to an element depending on a Json feed

Hit a slight bump on something.
So I have a spreadsheet feed coming through via json.
Once they are loaded, if they contain a certain word, I want an elment that is already on the page to do something.
Having some trouble.
Here is my code:
/*feed*/
function displayContent(json) {
var len = json.feed.entry.length
var divtag = ''
for (var i=0; i<len; i++) {
divtag += [
'<div id=' +' tooltipwrap' + i + '>' +
'<span style="font-size:22px; font-weight:600;">',
json.feed.entry[i].gsx$studentname.$t + ' ' +
'<span class="hide" style="font-size:18px; font-weight:300;">',
json.feed.entry[i].gsx$classlevel.$t
+ '</span>' + '<span id=' + 'tooltipside' + i +'>' +
json.feed.entry[i].gsx$gender.$t + '-' +
'</span>',
'</div>'
].join('');
}
document.getElementById('tipswrap').innerHTML = divtag
}
/* what I wanted to do */
if ($('#tooltipside0').html() === "Senior") {
$("#test1").addClass('no');
}
Here is the JSFiddle
Pay attention to the tabulation. Right now your code is hard to read because you have failed to do so.
Here:
var len = json.feed.entry.length
var divtag = ''
you are missing semi-colons. You have to put semi-colon at the end of any operation, like this:
var len = json.feed.entry.length;
var divtag = '';
Semi-colons serve as operation separators.
Here:
divtag += [
'' +
'',
json.feed.entry[i].gsx$studentname.$t + ' ' +
'',
json.feed.entry[i].gsx$classlevel.$t
+ '' + '' +
json.feed.entry[i].gsx$gender.$t + '-' +
'',
'</div>'
].join('');
You have multiple problems:
You have failed to put your html attributes into quotes, so the resulting html will be invalid. Also, you have used comma instead of plus at the last concatenation.
CONCLUSION: You are obviously not ready to implement this code, because:
- You lack Javascript syntax knowledge
- You lack HTML syntax knowledge
- You do not pay attention to tabulation
As a consequence, your main problem is not what the question states, namely, how to add a class to an element depending on JSON feed. Your main problem is that you lack Javascript and HTML education. Please, follow some tutorials to be able to solve a problem and after that try again to solve your problem. If you fail to do so, then you will have at least an educated guess.
After adding the content to tipswrap add the condition
document.getElementById('tipswrap').innerHTML = divtag; //$('#tipswrap').html(divtag)
if ($.trim($('#tooltipside0').html()) === "Senior") {
$("#test1").addClass('no');
}
Demo: Fiddle
I recommend you add a class to all of your rows called student and then from there use this javascript:
function displayContent(json) {
var len = json.feed.entry.length
var divtag = ''
for (var i = 0; i < len; i++) {
divtag +=
'<div class="student" id="tooltipwrap'+i+'">'+
'<span style="font-size:22px; font-weight:600;">'+
json.feed.entry[i].gsx$studentname.$t +
'<span class="hide" style="font-size:18px; font-weight:300;">'+
json.feed.entry[i].gsx$classlevel.$t +
'</span> '+
'<span id="tooltipside'+i+'">'+
json.feed.entry[i].gsx$gender.$t + '-' +
'</span>'+
'</span>'+
'</div>';
}
document.getElementById('tipswrap').innerHTML = divtag
}
jQuery(document).ready(function($) {
$('.student').each(function() {
if ($(this).text().toLowerCase().indexOf("senior") >= 0)
$(this).addClass('senior');
});
});
Here's a demo

JavaScript passing coordinates from one function to another

I am having issues passing two coordinates from one function to another. I don't really know JavaScript, but it seems to be somewhat correct. Could you please let me know where is my error?
<head>
<script>
var zoom = 12; // 18 for mobile phones because the geolocation is more accurate
function init() {
// Don't bother if the web browser doesn't support cross-document messaging
if (window.postMessage) {
if (navigator && navigator.geolocation) {
try {
navigator.geolocation.getCurrentPosition(function(pPos) {
send(pPos.coords.latitude, pPos.coords.longitude);
}, function() {});
} catch (e) {}
} else if (google && google.gears) {
// Relevant if targeting mobile phones (some of which may have Google Gears)
try {
var geoloc = google.gears.factory.create("beta.geolocation");
geoloc.getCurrentPosition(function(pPos) {
send(pPos.latitude, pPos.longitude);
}, function() {});
} catch (e) {}
}
}
}
function send(pLat, pLng) {
var myiframe = document.getElementById("myiframe").contentWindow;
// The third parameter, zoom, is optional
myiframe.postMessage(pLat + "," + pLng + "," + zoom, "http://www.qib.la");
}
window.onload=init;
</script>
</head>
<body>
<iframe id="myiframe" src="http://www.qib.la/embed/" width="400" height="400">
Check the prayer direction towards the Ka'ba in Makkah at
Qibla Direction.
</iframe>
<script type="text/javascript" src="http://praytimes.org/code/v2/js/PrayTimes.js"></script>
<br>
<p align="center">Waterloo, ON, Canada<p>
<div align="center" id="table"></div>
<script type="text/javascript">
var date = new Date(); // today
var times = prayTimes.getTimes(date, pLat + "," + pLng, -5);
var list = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha', 'Midnight'];
var html = '<table id="timetable">';
html += '<tr><th colspan="2">'+ date.toLocaleDateString()+ '</th></tr>';
for(var i in list) {
html += '<tr><td>'+ list[i]+ '</td>';
html += '<td>'+ times[list[i].toLowerCase()]+ '</td></tr>';
}
html += '</table>';
document.getElementById('table').innerHTML = html;
</script>
</body>
Is it possible to return a value from an asynchronous function? How do I use a callback here?
You have a syntax error in this code:
var times = prayTimes.getTimes(date, + b + ',' + c + , -5);
You have a "+" and then a comma immediately following it. I'm not sure what your intent for the code was, but that is what is causing it to not run.
Perhaps you intended to follow the pattern of appending the commas as strings?
var times = prayTimes.getTimes(date + ',' + b + ',' + c + ',' + -5);
Or perhaps that -5 was meant to be a separate argument?
var times = prayTimes.getTimes(date, b + ',' + c, -5);

Categories

Resources