mainDiv.innerHTML = external file - javascript

I have a code.js file which contains the following:
DivDialogHTML = function(){
var mainDiv = document.createElement("div");
mainDiv.id = "optin_settings_dialog";
mainDiv.className = "OptinDialog";
mainDiv.innerHTML = "<div>Text</div>";
}
The code to load the popup (dont know if it's all code, but to get the idea):
DivDialogOverlayHTML = function(){
var mainDiv = document.createElement("div");
mainDiv.id = "optin_settings_overlay_dialog";
mainDiv.className = "OptinDialog";
return mainDiv;
}
renderOptinWindow = function(){
var pageHead = document.getElementsByTagName("head")[0];
var pageBody = document.getElementsByTagName("body")[0];
if( pageHead && pageBody ){
pageBody.appendChild( this.getDivDialogHTML() );
}
}
Instead of using the mainDiv.innerHTML = '<div>Text</div>' I'd like the mainDiv.innerHTML to open another file (Dialog.html).
How do I do that?

with Ajax. But why not using jQuery?
$('.selector').load(url);
In your case you have to insert jQuery first like this in your
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
And than take your existing function and change it like this
DivDialogHTML = function(){
var $mainDiv = jQuery("div");
$mainDiv.attr('id', "optin_settings_dialog");
$mainDiv.addClass("OptinDialog");
/* $mainDiv.html("<div>Text</div>"); */
$mainDiv.load('Dialog.html');
}

Do you mean another window? If so, please take a look at window.open
window.open
After you create new window, you put its contents and display

if you don't want to use jQuery you can use an iframe
HTML
<iframe id="optin_settings_dialog"></iframe>
Javascript
document.getElementById("optin_settings_dialog").src="Dialog.html";

Related

Customizing the JS/CSS in a TrustPilot widget

I am trying to modify the TrustPilot widget on my site.
The basic structure of the TrustPilot widget is:
#tp-widget_wrapper .tp-widget-wrapper
#wrapper-top .wrapper-top
#tp-widget-reviews-wrapper .tp-widget-reviews-wrapper hidden-element
#tp-widget-reviews .tp-widget-reviews
.tp-widget-review
.tp-widget-stars
.date
I am trying to hide the div .date.
What I have gotten so far is:
var trustpilot_children = document.getElementById("trustpilot_widget").childNodes;
var trustpilot_frame = trustpilot_children[0];
var date_tags = trustpilot_frame.document.getElementsByClassName("date");
date_tags.style.display = "none";
However I get the error:
Uncaught TypeError: Cannot read property 'getElementsByClassName' of undefined
The var trustpilot_frame is finding the iframe, I just can't access anything within it.
Edit
var trustpilot_children = document.getElementById("trustpilot_widget").childNodes;
var trustpilot_frame = trustpilot_children[0].contentDocument;
console.log(trustpilot_frame);
var date_tags = trustpilot_frame.getElementsByClassName("date");
console.log(date_tags);
date_tags.style.display = "none";
Console:
Edit 2
var trustpilot_children = document.getElementById("trustpilot_widget").childNodes;
var trustpilot_frame = trustpilot_children[0].contentDocument;
var style_tag = trustpilot_frame.createElement("style");
style_tag.textContent = ".date{display:none;}";
trustpilot_frame.getElementsByTagName("head")[0].appendChild(style_tag);
console.log(trustpilot_frame);
Console:
Edit 3
var trustpilot_children = document.getElementById("trustpilot_widget").childNodes;
var trustpilot_frame = trustpilot_children[0].contentDocument;
trustpilot_frame.onload = setTimeout(hide_dates, 10000);
function hide_dates(){
// method 1
var style_tag = trustpilot_frame.createElement("style");
style_tag.textContent = ".date{display:none;}";
trustpilot_frame.getElementsByTagName("head")[0].appendChild(style_tag);
console.log(trustpilot_frame);
// method 2
var date_tags = trustpilot_frame.getElementsByClassName("date");
console.log(date_tags);
date_tags.style.display = "none";
}
Console shows the same as EDIT2 for the dom and the first EDIT for date_tags
https://codepen.io/phallihan/pen/OdwgGd
To get the document of an iframe you need to use document.getElementById('iframe').contentDocumentyou should then be able to use getElementsByClassName
https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/contentDocument
Your updated code would look like:
var trustpilot_children = document.getElementById("trustpilot_widget").childNodes;
var trustpilot_frame = trustpilot_children[0];
var date_tags = trustpilot_frame.contentDocument.getElementsByClassName("date");
date_tags.style.display = "none";
Update
Try the below to wait for the iframe to load.
var trustpilot_children = document.getElementById("trustpilot_widget").childNodes;
var trustpilot_frame = trustpilot_children[0];
trustpilot_frame.onload = function() {
var date_tags = trustpilot_frame.contentDocument.getElementsByClassName("date");
date_tags.style.display = "none";
}
I did not want to do this but I am a lowly developer and my boss insisted. I was unable to do this via JS/CSS so ended up having to replace the snippet with my own slider and save reviews as images.

Inserting CSS-linked HTML in HTML page code via JS

I do not have access to the HTML of the pages (they are program-built dynamically).
I do have access to the JS page it is linked to.
For example I can do somethin like this and it works:
window.onload=function(){
var output = document.getElementById('main_co');
var i=1;
var val="";
while(i<=1)
{ if(!document.getElementById('timedrpact01'+i))
{
var ele = document.createElement("div"); ele.setAttribute("id","timedrpact01"+i);
ele.setAttribute("class","inner");
ele.innerHTML=" Hi there!" ;
output.appendChild(ele);
I would like to use this basis insert a button that would allow to switch from one CSS set (there are several files invoked) to another _another path.
Many thanks
The external stylesheets are referenced using link, as in:
<link rel="stylesheet" href="http://example.com/path-to-css">
So, get hold of the appropriate link element using:
var css = document.getElementsByTagName("link")[0];
Here, we got hold of the first link available by specifying the [0] index.
Then, overwrite the href attribute to point it to the new path.
css.setAttribute("href", "http://example.com/path-to-css");
window.onload=function(){
var output = document.getElementById('main_co');
var i=1;
var val="";
//switch all the href's to another path
var switchStyleSheet = function() {
var links = document.getElementsByTagName("link");
for(var i=0; lkC = links.length; i < lkC; i++)
links[0].href = links[0].href.replace('path_to_file', '_path_to_file');
};
while(i<=1) //while is not required here, if i is 1
{
if(!document.getElementById('timedrpact01'+i)) {
var ele = document.createElement("div"); ele.setAttribute("id","timedrpact01"+i);
ele.setAttribute("class","inner");
ele.innerHTML=" Hi there!" ;
var button = document.createElement('button');
if(button.addEventListener) {
button.addEventListener('click', switchStyleSheet);
}
else {
button.attachEvent('click', switchStyleSheet);
}
output.appendChild(button);
output.appendChild(ele);
}
}
}

Manipulating DOM data without affecting the view

<!DOCTYPE html>
<html><body>
<p id="intro">Hello <em id="abcd">intro</em> World!</p>
<script type="text/javascript">
var txt=document.getElementById("intro").innerHTML;
var el = document.createElement("span");
el.innerHTML = txt;
var aa = el.getElementById("abcd").innerHTML;
alert( aa );
</script>
</body></html>
The above is a simple snippet. Actually I have an HTML editor and when the user saves the data I should save only the required content. Here I am getting the content of an element and manipulating it with DOM and pass the details to the server. This way I will not change the page content (user view remains the same) and he/she will continue editing the document.
The above is a simple example but in the real case I have to remove, change and move certain elements. The above code fails el.getElementById("abcd").innerHTML. Appreciate any pointers.
You can create a hidden iframe to manipulate all your changes, thus creating a separate DOM, then simply pull back the results you want.
var iframe;
if (document.createElement && (iframe = document.createElement('iframe'))) {
iframe.name = iframe.id = "externalDocument";
iframe.className = "hidden";
document.body.appendChild(iframe);
var externalDocument;
if (iframe.contentDocument) {
externalDocument = iframe.contentDocument;
} else if (iframe.contentWindow) {
externalDocument = iframe.contentWindow.document;
}
else if (window.frames[iframe.name]) {
externalDocument = window.frames[iframe.name].document;
}
if (externalDocument) {
externalDocument.open();
externalDocument.write('<html><body><\/body><\/html>');
externalDocument.close();
/* Run your manipulations here */
var txt = document.getElementById("intro").innerHTML;
var el = document.createElement("span");
el.innerHTML = txt;
/* Attach your objects to the externalDocument */
externalDocument.body.appendChild(el);
/* Reference the externalDocument to manipulate */
var aa = externalDocument.getElementById("abcd").innerHTML;
alert(aa);
}
/* Completed manipulation - Remove iFrame */
document.removeChild(iframe);
}
I have it working here:
http://jsfiddle.net/ucpvP/
Try using jQuery like given below.
function SaveData() //Your add function
{
var txt=$("#intro").html();
$(document).append("<span id='abcd'>" + txt+ "</span>");
var aa = $("#abcd").hmtl();
alert(aa);
}
You can use a DOM Element that is never appended to the DOM.
I use this 'cleanup' function:
function cleanup(str){
var tester = document.createElement('div'),
invalid, result;
tester.innerHTML = str;
//elements I don't allow
invalid = tester.querySelectorAll('script,object,iframe,style,hr,canvas');
// the cleanup (remove unwanted elements)
for (var i=0;i<invalid.length;(i+=1)){
invalid[i].parentNode.removeChild(invalid[i]);
}
result = tester.innerHTML;
tester = invalid = null;
//diacritics to html-encoded
return result.replace(/[\u0080-\u024F]/g,
function(a) {return '&#'+a.charCodeAt(0)+';';}
)
.replace(/%/g,'%25');
}
//usage:
cleanup(document.getElementById("intro").innerHTML);
You can extend the function with your own code to remove, change and move certain elements.

Getting HTML value from Tinymce

Is there a way to get HTML contents from TinyMCE editor using jQuery so I can copy this over to another div?
I tried several methods like val() on content but it doesn't seem to be working...
if you are initilizing with jquery adaptor
$(selector).tinyMCE().getContent();
Using jQuery:
<textarea id="content" name="content">
$('#content').html()
Using TinyMce API:
$('#content').tinymce().activeEditor.getContent() // overall html
$('#content').tinymce().activeEditor.getContent({format : 'text'}) // overall text
$('#content').tinymce().selection.getContent() // selected html
$('#content').tinymce().selection.getContent({format : 'text'})) // selected text
if you are using tinymce, i would use it's internal methods to get the content you need. when i need to get content within the active editor, i do this:
var rawString = tinyMCE.activeEditor.getContent();
i invoke that method within an event handler function.
here is the documentation:
tinymce api
use TinyMCE's API to get it:
alert(tinyMCE.activeEditor.getContent());
Use text(); instead of val();.
I was trying charlietfl method: $(selector).tinyMCE().getContent();
There was an error:
[$(selector).tinyMCE().getContent();][1]
This way with activeEditor worked for me:
activeEditor
tinymce.activeEditor.getContent()
Source
Here is my code:
$(document).ready(function() {
$(document).on("click", ".btnClassClose", function () {
var tinyMCEcontent = tinymce.activeEditor.getContent();
var getAttrIDArray = [];
$("#" + getelementId).html("");
$("#" + getelementId).html(tinyMCEcontent);
$("#" + getelementId).append(buttonEDI);
var PageName = new Object();
PageName["mdlPageId"] = getelementId;
getAttrIDArray.push(PageName);
var PageName = new Object();
PageName["mdlPageContentHtml"] = tinyMCEcontent;
getAttrIDArray.push(PageName);
var PageName = new Object();
PageName["mdlPageName"] = "Default";
getAttrIDArray.push(PageName);
var PageName = new Object();
PageName["mdlAligen"] = "Central";
getAttrIDArray.push(PageName);
var PageName = new Object();
PageName["mdlOrderNumberHorizontal"] = "1";
getAttrIDArray.push(PageName);
alert(JSON.stringify(getAttrIDArray));
var contentGetAttrIDArray = SecondMainSendAjax("CMS?handler=Content", getAttrIDArray);
});
});

JavaScript changing on click

I'd like some help changing this JavaScript onclick event to just load the data on page the page load...
Preferably not using the body on load tag...
So obviously I'd pre-set the var for term inside the script term rather than the existing on click event..
Hope that made sense.
<p><a id="keywordlink" href="?term=wombats">Get keywords for wombats</a></p>
<script type="text/javascript" src="keywords.js"></script>
<script type="text/javascript">
var x = document.getElementById('keywordlink');
if(x){
x.onclick = function(){
var term = this.href.split('=')[1];
this.innerHTML += ' (loading...)';
KEYWORDS.get(term,seed);
return false;
}
}
function seed(o){
var div = document.createElement('div');
var head = document.createElement('h2');
head.innerHTML = 'Keywords for '+o.term;
div.appendChild(head);
var p = document.createElement('p');
p.innerHTML = o.toplist;
div.appendChild(p);
var head = document.createElement('h3');
head.innerHTML = 'Details:';
div.appendChild(head);
var list = document.createElement('ol');
for(var i=0,j=o.keywords.length;i<j;i++){
var li = document.createElement('li');
li.innerHTML = o.keywords[i].term + '('+o.keywords[i].amount+')';
list.appendChild(li);
}
div.appendChild(list);
x.parentNode.replaceChild(div,x);
}
</script>
change this:
if(x){
x.onclick = function(){
var term = this.href.split('=')[1];
this.innerHTML += ' (loading...)';
KEYWORDS.get(term,seed);
return false;
}
}
to something like this:
function loadSomething(){
var term = x.href.split('=')[1];
x.innerHTML += ' (loading...)';
KEYWORDS.get(term,seed);
return false;
}
loadSomething();
you can leave it where it is, but for readability, put it below the seed function.
You should use something like onload or document.ready, but alternatively you can move the whole script file to the bottom of the page
Don't set the event handlers that way. Use addEventListener and (for IE) attachEvent.

Categories