How to append the HTML code snippet to HTML iframe using jquery? - javascript

How to append the HTML code snippet to HTML iframe using jquery? Actually, I have added an HTML code snippet in MySQL Database using PHP. Now I have fetched that HTML Code snippet and trying to append that HTML code snippet in iframe using jquery.
$( document ).ready(function() {
var snippets='<?php echo $snippets_preview; ?>';
$(function() {
var $iframe = $('#iframehtml');
$iframe.ready(function() {
$iframe.contents().find("body").append(snippets);
});
});
});
But I am getting the following error
Uncaught SyntaxError: Invalid or unexpected token
snippets_preview has the following value in it. when I change the value of snippet_preview. it works fine.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>'.$postdata['snippets_css'].'</style>
<script>'.$postdata['snippets_javascript'].'</script>
</head>
<body>
'.$ContentDecodedHTML.'
</body>
</html>

If you want to embed html code in an iframe you have to do for example:
JAVASCRIPT (class)
<script>
// -------------------------------------------------------- CLASS
var class_iframe = {
// ------------------------------------- STEP 1 (Create an new Iframe)
generateIframe: function(src, targetDOM){
// ---------------- Create iframe
var newIframe = document.createElement('iframe');
newIframe.onload = function(){
class_iframe.getIframe($('.iframehtml').contents());
};
newIframe.src = src;
newIframe.className = "iframehtml";
newIframe.frameBorder = "0";
// ---------------- Insert iframe in DOM
$(targetDOM).replaceWith(newIframe);
},
// ------------------------------------- STEP 2 (Get iframe in this class)
getIframe: function(iframe){
class_iframe.frame = iframe; console.log(class_iframe.frame);
},
// ------------------------------------- STEP 3 (Append in this iframe)
appendIframe: function(targetInIframe, content){
console.log(class_iframe.frame);
$target = class_iframe.frame.find(targetInIframe); console.log($target);
$target.prepend(content);
},
}
// -------------------------------------------------------- ACTION (loadPage)
$(document).ready(function(){
//$("body").prepend(`<div id="insertIframe"></div>`); //Just for the test
class_iframe.generateIframe("your_url_iframe.html", "#insertIframe");
});
</script>
In your html page
<div id="insertIframe"></div>
JAVASCRIPT (for append in your new iframe)
<script>
// -------------------------------------------------------- ACTION (after loadPage)
class_iframe.appendIframe("html", `<div class="insert">Hello world !</div>`);
</script>

Related

Creating an element inside class which is part of included html using javascript *no jquery

I'm trying to load some HTML code through a XMLHttpRequest into my index.html. But I'm blocked by appending the received HTML code to another tag in my index.html.
This is my index.html with the XMLHttprequest:
<header id="header"></header>
<script>
if (document.body.contains(document.getElementById('header'))) {
var reqHeader = new XMLHttpRequest();
reqHeader.onload = function () {
document.getElementById('header').appendChild(this.responseText);
}
reqHeader.open('get', 'header.html', true);
reqHeader.send();
}
</script>
And this the content of my header.html file:
<div id="headerWrapper">
<ul>
<li id="foo">1</li>
</ul>
</div>
The content returned by the XMLHttpRequest is a String. You can parse that String using the javascript XMLParser, which will returns you a DOM element that you can access with usual javascript DOM accessing syntax.
So in your XMLHttpRequest, use the following code
const parser = new DOMParser().parseFromString(htmlString, 'text/html');
document.getElementById('header').appendChild(parser.querySelector('#headerWrapper'));
Simplified example without XMLHttpRequest because of cross origin policy:
if (document.body.contains(document.getElementById('header'))) {
var htmlString = '<div id="headerWrapper"><ul><li id="foo">1</li><li id="bar">2</li></ul></div>';
const parser = new DOMParser().parseFromString(htmlString, 'text/html');
document.getElementById('header').appendChild(parser.querySelector('#headerWrapper'));
}
document.getElementById('foo').classList.add('test');
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<header id="header"></header>
</body>
</html>

JavaScript: Read directory from within addEventListener function

I added an event listener to my website which should add a date, time and device-id to the website. These information are included in the filenames of some files located in a directory at the same level as my index.html.
Directory Structure:
- audiofiles
-- date_time_device.wav
-- date2_time2_device2.wav
- scripts
-- scripts.js
- Home.html
Within the head of Home.html I'm calling a addContent() (located in scripts.js) which includes the addEventListener().
This works if I'm inserting hardcoded strings, so it seems that reading from the directory does not work.
It would be great if anybody could steer me into the right direction. Thanks!
Head of Home.html:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/wavesurfer.js"></script>
<script type="text/javascript" src='scripts/scripts.js'> </script>
<script type="text/javascript" src="js/wavesurfer.js"></script>
<script>
addContent();
</script>
<title>Home</title>
</head>
scripts.js:
function addContent() {
document.addEventListener("DOMContentLoaded", function(event) {
var fs = require('fs');
const files = fs.readdirSync('path/to/audiofiles');
for (i=0;i<3;i++) {
var date = files[i].slice(0,10);
var time = files[i].slice(11,19);
var device = files[i].slice(20,-4);
var TheInnerHTML ="";
TheInnerHTML += "<tr><td> blabla" + 3 + " " + String(date)+"</td><td>"+String(time)+"</td></tr>"+String(device)+"</td></tr><br>";
}
document.getElementById("TheBody").innerHTML = TheInnerHTML;
});
}

Routing(?) in Vanilla JS

I need my webite to display info in a certain language, based on a query in my webite's URL (e.g. www.website.com/index.php?country=FR). How can I do that with vanilla JS and not React/Angular?
My approach:
1) JS recognizes a query in the URL (in this case- 'country=FR') and then appends a js file, which has neccessary french words in it defined by variables.
2) JS in my script tag that's in the HTML file, appends the main page markup text with template literals in it.
3)
I don't know, whether the browser fails to either fetch the language file itself or its variables. At the moment it does not render anything.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./js/main.js"></script>
</head>
<body>
<script>
const template= `
<h1>Good Morning: ${goodmorning} </h1>
<h2>Good Evening: ${goodevening} </h2>
<h3>My name is: ${mynameis}</h3>`
function markupAppend() {
$('body').html(template);
console.log('Markup loaded')
}
markupAppend()
</script>
</body>
</html>
=========================
Main.js
var domain = window.location.href;
var FRString = domain.includes("country=FR");
var ESString = domain.includes("country=ES");
if (FRString) {
$('head').append(`<script src="./Language_files/FRENCHwords.js" />`)
}
if (ESString) {
$('head').append(`<script src="./Language_files/SPANISHwords.js" />`)
}
=========================
FRENCHwords.js
const goodmorning = 'Bonjour';
const goodevening = 'Bonsoir';
const mynameis = 'Mon nom est';
=========================
SPANISHwords.js
const goodmorning = 'Buenos dias';
const goodevening = 'Buenas tardes';
const mynameis = 'Mi nombre es';
No errors displayed, the page is just not rendering...
In Your main.js file, you are using domain.includes, it only returns the domain name but not the entire URL. You can use window.location.href.includes for this.
Instead of: domain.includes("country=FR");
Try: window.location.href.includes("country=FR");

Compare data attributes of dynamically created elements with JQuery

I'm making a game where after you click an image it will shuffle the array and repopulate the DOM. The idea is that you can't click the same image twice even though the images in the array are shuffled.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Document</title>
</head>
<body>
<!-- Tribute to Tom Whalen for the awesome Transformers pictures -->
<button id="shuffleButton" type="submit">Shuffle</button>
<div id="test"></div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="app.js">
</script>
</body>
</html>
The #testDiv is populated on page load and each time you click it shuffles the array and repopulates #testDiv.
Each image in the object has a name property related to the character's image.
I'm using Transformers.
Here's an example from the array of objects I am using.
var images = [
{
name: "bumblebee",
image: "assets/images/bumblebee.jpg"
},
{
name: "frenzy",
image: "assets/images/frenzy.jpg"
}];
JavaScript
/*Working for loop through images array */
function loop() {
for (var i =0; i < images.length; i++) {
var testImage = $('<img class="images">')
.attr('src', `${images[i].image}`)
.attr('data', `${images[i].name}`);
$(testDiv).append(testImage);
};
};
loop();
function Shuffle() {
images.sort(function(a, b) {
return 0.5 - Math.random()
});
loop();
};
$("#shuffleButton").on('click', function(){
$(testDiv).empty();
Shuffle();
console.log(images);
});
var count = 0;
$(document).on('click', '.images', function() {
$(testDiv).empty();
Shuffle();
console.log($(this).data());
});
I am assigning the name property to a data attribute and want to compare the data attributes with a click function.
When I console.log($(this).data()); I get a blank object with ___proto___ : Object and not the data attribute.
How would I grab the data attribute?
How woinI then store that into a variable?
How would I compare that data attribute inside of a variable to another element's data attribute?
You will need to send the data attributes name for your console.log function.
console.log($(this).data('name'));
I have attached an example below.
$(document).on('click', '#div', function() {
alert($(this).data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div" data-id="test" >hello</div>

Firefox not executing scripts loaded dynamically via another external script

I've been having trouble with Firefox not executing JavaScript files that were loaded dynamically via an external script.
Let me explain.
I have the following HTML file:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Restive.JS</title>
<meta name="keywords" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" src="assets/js/load.js"></script>
</head>
<body>
<h1>Loading JavaScript</h1>
</body>
</html>
Inside my load.js file, I have the following code:
document.addEventListener("DOMContentLoaded", function() {
function loadScript(url) {
var script = document.createElement("script");
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
var list_arr = ['assets/js/test1.js', 'assets/js/test2.js'];
for (var i = 0; i < list_arr.length; i++) {
loadScript(list_arr[i]);
}
});
And inside test1.js and test2.js, I have console.log('test1.js is loaded!'); and console.log('test2.js is loaded!');.
The problem is that test1.js and test2.js are loaded (I can see both files in the <head> via inspection), but they are never executed (because no messages appear in the console log).
However, when I change the format of script reference in my original HTML by inlining the JavaScript i.e. changing from this:
<script type="text/javascript" src="assets/js/load.js"></script>
to this:
<script>
document.addEventListener("DOMContentLoaded", function() {
function loadScript(url) {
var script = document.createElement("script");
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
var list_arr = ['assets/js/test3.js', 'assets/js/test4.js'];
for (var i = 0; i < list_arr.length; i++) {
console.log('i = ' + i);
loadScript(list_arr[i]);
}
});
</script>
Then the scripts are loaded and executed.
I don't see this behaviour in Chrome or Safari, only Firefox. Also, inlining is not an option because this functionality is built-in to a library that users will have to reference via an external link.
Is this a problem that is fixable?
EDIT
I'm on a Mac OSX 10.10.5 using Firefox 46.0.1

Categories