I am new to Javascript and are trying to become better.
I was wondering how i can with the help och template-tag load the image in it if a Image is unsafe like from a http-source. Think of it like a email-client asking you if you want to load in images if not then it breaks the src. like src=temp-data, and when clicked to download and show the images then it sets the src to the correct one. here is the code i have written thus far
function removeUnsafeImgLinks(bodyContent) {
let _bodyContent = bodyContent
const el = document.createElement('template');
el.innerHTML = _bodyContent
const nodes = el.querySelectorAll('img[src^="http://"]');
if (nodes.length > 0) {
nodes.forEach((x => {
x.innerHTML.replace("src=temp-data")
}));
}
iframe.srcdoc = el.innerHTML;
return newBod;
}
Anyone got any tip or solution?
x.innerHTML.replace("src=temp-data") does not actually change anything
Fixing your syntax errors you might mean
const removeUnsafeImgLinks = bodyContent => {
const el = document.createElement('template');
el.innerHTML = bodyContent
const imgs = [...el.querySelectorAll('img[src^="http://"]')];
if (imgs.length>0) {
imgs.forEach(x => x.src='temp-data')
iframe.srcdoc = el.innerHTML;
}
};
Related
I use MathJax to display formulas and more things in math. Like square root, limits, logarithm etc..
I have array of objects. Every object has 2 values. Question, Answer
/Objects/Matematika1.js
export const examples = [
{
question: "\\(ax^2 + bx +c = 0\\)",
answer: "(answer for 1)",
},
How app works:
In the menu i click something for example Math (Matematika1). Menu is standart <a href> with onClick function and ID. The function gets the ID and save it in localStorage
Menu Item
Matematika#1
I have a localStorage array but i need only ID as string.
let selectedPage = localStorage.getItem("page-value");
selectedPage.toString();
And then i need the value of selectedPage insert to import path. Object has same name as ID in menu item
//localStorage array to string variable
let selectedPage = localStorage.getItem("page-value");
selectedPage.toString();
//import { examples } from "./Objects/Matematika1.js";
//importing the array from /object/"selectedPage"
import("./Objects/" + selectedPage + ".js")
.then((array) => {
const { examples } = array;
//console.log(array);
function toggle(i) {
const div = document.querySelector(`#result_${i}`);
if (div.style.display !== "none") {
div.style.display = "none";
} else {
div.style.display = "block";
}
}
const container = document.querySelector("#examples-container");
examples.forEach((ex, i) => {
const card = document.createElement("div");
card.classList.add("card");
const example = document.createElement("div");
example.classList.add("example");
example.innerHTML = ex.question;
card.appendChild(example);
const button = document.createElement("button");
button.classList.add("toggle");
button.innerHTML = "Toggle";
button.addEventListener("click", () => toggle(i)); // Here is the event listener
card.appendChild(button);
const result = document.createElement("div");
result.id = "result_" + i;
result.style.display = "none";
result.classList.add("result");
result.innerHTML = ex.answer;
card.appendChild(result);
container.appendChild(card);
});
})
.catch((err) => {
console.log(err);
});
My issue is when i comment these lines and set static import path. MathJax render is working very well. But i need set import path dynamicly and in this case MathJax is not working.
import("./Objects/" + selectedPage + ".js")
.then((array) => {
const { examples } = array;
})
.catch((err) => {
console.log(err);
});
To be honest i have no idea what's wrong. The import("..").then().catch() i copied from this forum. In DOM i can't see any MathJax class so it look's JS don't have access to MathJax Library?
<div id="examples-container"></div> and also MathJax imported in index.html
I’m Rahul and I’m new to coding. I have a query related to DOM event. Please look at the following code snippet -
let door1 = document.getElementById('one');
door1.src = "closed_door.svg";
const isClicked = (door) => {
if(door.src === "closed_door.svg") {
return true;
}
else {
return false;
}
};
door1.onclick = () => {
if(isClicked(door1)) {
door1.src = "beach.svg";}
};
To give you brief, one is an id for an element. Without isClicked, I am able to successfully change the src from closed door to beach on clicking. But when I introduce isClick, it doesn’t change. Can someone please tell me what I’m missing. I’ll be very thankful
Note - I'm building game similar to this - https://s3.amazonaws.com/codecademy-content/projects/chore-door/chore-door-final/index.html They are using the same process as mine. So please suggest a solution that tells me about the error I'm making here rather than an alternative to the problem
Regards
Rahul
As reported here:
the src reflected property will be the resolved URL — that is, the absolute URL that that turns into. So if that were on the page http://www.example.com, document.getElementById("foo").src would give you "http://www.example.com/images/example.png".
so to get the real src attribute you should use .getAttribute('src') like so:
const isClicked = (door) => {
if(door.getAttribute('src') === "closed_door.svg") {
return true;
}
else {
return false;
}
};
Ans also BTW, you can just shortcut it to:
const isClicked = (door) => door.getAttribute('src') === "closed_door.svg";
Replace your code with this..
let door1 = document.getElementById('one');
door1.src = "https://s3.amazonaws.com/codecademy-content/projects/chore-door/images/closed_door.svg";
const isClicked = (door1) => {
if(door1.src === "https://s3.amazonaws.com/codecademy-content/projects/chore-door/images/closed_door.svg") {
return true;
}
else {
return false;
}
};
door1.onclick = () => {
if(isClicked(door1)) {
door1.src = "https://s3.amazonaws.com/codecademy-content/projects/chore-door/images/beach.svg";}
};
As an example, I have this code that is able to add the title of a page as a parameter to a link that is identified as an ID. I would like to be able to do the same for the language of the page. Thanks for your help!
<script>
const linkIds = [
'Your_link_id'
];
linkIds.forEach(id => {
const interval = setInterval(() => {
const link = document.querySelector('#' + id);
if (link) {
clearInterval(interval);
const href = link.getAttribute('href');
const pageTitle =
document
.title
.replace(/\s+/g, '_')
.replace(/&/g, '')
.toLowerCase()
const newHref = `${href}?your_parameter_name=${pageTitle}`;
link.setAttribute('href', newHref);
}
}, 20);
});
</script>
To get language of the page you have to get lang property from the document element. I created an example code which gets and sets the language of the page. You can save the output to some variable and create a link with it.
let lang = document.documentElement.lang
console.log(lang)
// output: en
document.documentElement.lang = 'af'
console.log(document.documentElement.lang)
// output: af
I added this as a new answer because I am not sure what I am suppose to do (this fact itself shows that this is not very well written question) but I will try.
So your script uses some array of IDs. Then it creates an interval for each ID that constantly updates the href attribute of element with that ID with some value. I don't know why would you do that as pageTitle or language is not changing over time but I might just stop asking so here is the edited code:
<script>
const linkIds = [
'Your_link_id'
];
// here I get the lanugage of the page
let lang = document.documentElement.lang;
linkIds.forEach(id => {
const interval = setInterval(() => {
const link = document.querySelector('#' + id);
if (link) {
clearInterval(interval);
const href = link.getAttribute('href');
// here I set the language where page title was before
const newHref = `${href}?your_parameter_name=${lang}`;
link.setAttribute('href', newHref);
}
}, 20);
});
</script>
Try it and report back. If you need to use such a complex script, it might do you good to actually learn Javascript.
So I have this code:-
const extendCSS = (el1, el2) =>{
Array.prototype.slice.call(document.querySelector(el1).attributes).forEach(function(item) {
el2.setAttribute(item.name, item.value);
});
}
const build = (elementType) => tag => {
const query = document.querySelectorAll(tag);
query.forEach(ptag => {
const shadow = ptag.attachShadow({
mode: 'open'
});
const element = document.createElement(elementType);
element.innerHTML = ptag.innerHTML;
extendCSS(tag, element);
element.setAttribute('id', tag);
shadow.host.parentNode.replaceChild(element, shadow.host);
});
};
const h1 = build('h1');
const textarea = build('textarea');
textarea("text-editor");
h1("text-value");
const texteditor = document.querySelector('#text-editor');
const textvalue = document.querySelector('#text-value');
texteditor.addEventListener('keydown', ()=>{
textvalue.innerHTML = texteditor.value;
});
<text-editor></text-editor>
<text-value></text-value>
This build() does one thing:- it selects the custom element, changes its tag type and assign a id of name of the custom tag and replaces it with the desired thing. It is working fine here. but if I code all the thing after the build function in a external .js file and then bind it to the html and run it, but it won't work. How can I resolve this? This is a very important for now.
Help and answers appreciated. Thanks in advance.
I'm trying to create a basic WYSIWYG editor where I can click on elements in a sidebar and have those element written to an iFrame page.
My current setup has me creating an array of JSX elements that I then write to a react-iframe via a contentDocument write call.
The problem is that right now when I attempt to add these components, I get an [object Object] printed in the iFrame. Attempting to JSON.stringify() said object only gives me a literal printout of the object and not a render of the JSX element itself.
Please give me constructive criticism and any ideas on better ways to go about this- this has been my naïve attempt based on what I currently know.
Code:
SetIFrameInnerHTML(){
//get snapshot from React's state
const snapshot = this.state.PagesSnapshot;
//if the snapshot exists
if(snapshot){
const currPage = document.querySelector('#page_selector').value;
//Variable I'll be storing array to print to page will be
var pageTags = [];
//Fetching data from my dB and setting variables...
snapshot.forEach(function (childSnapshot){
let testValue = childSnapshot.val();
if(currPage == Object.keys(testValue.pages)[0]){
const currPage = document.querySelector('#page_selector').value;
console.log('break');
var tagType_pt1 = testValue.pages
var tagType_pt2 = tagType_pt1[currPage];
var tagType = tagType_pt2.tags[0].tag_type;
var tagStyle_pt1 = testValue.pages
var tagStyle_pt2 = tagStyle_pt1[currPage];
var tagStyle = tagStyle_pt2.tags[0].style;
var tagContent_pt1 = testValue.pages;
var tagContent_pt2 = tagContent_pt1[currPage];
var tagContent = tagContent_pt2.tags[0].content;
if(tagType == 'p'){
pageTags.push(<p style = {tagStyle}>{tagContent}</p>);
}else if(TagType == 'img'){
pageTags.push(<img src = {imageSrc}></img>);
}
}
});
let editorFrame = document.getElementById('iFrameId');
// also tried: editorFrame.postMessage(pageTags, 'http://localhost:8080/', false);
editorFrame.contentDocument.write(pageTags);
//also tried: editorFrame.contentDocument.write(JSON.stringify(pageTags));
}
}
//Rendering the iframe
render(){
return(
<div>
... some JSX tags
<Iframe
id = "VisualEditorWindow"
url = {this.props.CurrentEditPageHandle}
ref = {this.VisualLogic}
width = "calc(100vw - 500px)"
height = "90vh"
className = "iframe"
display="initial" />
</div>
);
}
charlieftl's idea worked:
One suggestion would be pass all that to a component you render off screen and use a ref or ReactDOM.findDOMNode to access the outer element and then get it's outerHTML to write to iframe