I am making my iframe to display an HTML string as a webpage. However I can't seem it get it right.
Iframe has to display a html string which has been returned by a JavaScript function. This html string has been extracted from the current HTML page on which the script will run.
HTML page:
<body>
<pre> This is my test page for testing . Check the html Sample below:<br><BODY></br><p>Hello World</p><br></BODY></br>HTML sample </pre>
</body>
Javascript:
(function(){
// the minimum version of jQuery we want
var v = "1.3.2";
// check for jQuery. if it exists, verify it's not too old.
if (window.jQuery === undefined || window.jQuery.fn.jquery < v) {
var done = false;
var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/" + v + "/jquery.min.js";
script.onload = script.onreadystatechange = function(){
if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
initMyBookmarklet();
}
};
document.getElementsByTagName("head")[0].appendChild(script);
} else {
initMyBookmarklet();
}
function initMyBookmarklet() {
(window.myBookmarklet = function() {
function getSelText() {
var test = document.body;
var text = test.textContent;
var bodyStart="<BODY";
var bodyEnd="</BODY>";
var lim1=text.indexOf(bodyStart);
var lim2=text.indexOf(bodyEnd);
var printstr=text.substring(lim1-bodyStart.length,lim2+bodyEnd.length);
return printstr;
}
if ($("#wikiframe").length == 0) {
var s = "";
s = getSelText();
if (s == "") {
var s = prompt("Forget something?");
}
if ((s != "") && (s != null)) {
var content = "<html>" + s + "</html>";
$("body").append("\
<div id='wikiframe'>\
<div id='wikiframe_veil' style=''>\
<p>Loading...</p>\
</div>\
<iframe id='wikiIDframe'></iframe>\
<style type='text/css'>\
#wikiframe_veil { display: none; position: fixed; width: 100%; height: 100%; top: 0; left: 0; background-color: rgba(255,255,255,.25); cursor: pointer; z-index: 900; }\
#wikiframe_veil p { color: black; font: normal normal bold 20px/20px Helvetica, sans-serif; position: absolute; top: 50%; left: 50%; width: 10em; margin: -10px auto 0 -5em; text-align: center; }\
#wikiframe iframe { display: none; position: fixed; top: 10%; left: 10%; width: 80%; height: 80%; z-index: 999; border: 10px solid rgba(0,0,0,.5); margin: -5px 0 0 -5px; }\
</style>\
</div>");
$("#wikiIDframe").contents().find('body').append(s);
$("#wikiframe_veil").fadeIn(750);
}
} else {
$("#wikiframe_veil").fadeOut(750);
$("#wikiframe iframe").slideUp(500);
setTimeout("$('#wikiframe').remove()", 750);
}
$("#wikiframe_veil").click(function(event){
$("#wikiframe_veil").fadeOut(750);
$("#wikiframe iframe").slideUp(500);
setTimeout("$('#wikiframe').remove()", 750);
});
})();
}
})();
Here's a link to JSFiddle for the same. JSFiddle
Could anybody please help me out with this.
Thanks
Related
So I made a code block that you can edit and create a new code block, but the problem is that It's not creating the code tag. Here is my code:
<style>
html, body {
margin-top: 5px;
}
.codeblockDiv {
width: 50%;
}
.codeblock {
background: linear-gradient(to top, rgb(207, 207, 207) 16%, rgb(252, 252, 252) 79%);
border: 1px solid;
border-radius: 5px;
padding: 4px;
width: 50%;
display: inline-block;
outline: none;
}
.edit {
top: 0;
right: 300px;
position: absolute;
}
.cancel {
top: 0;
right: 350px;
position: absolute;
}
.new {
left: 9px;
top: 0;
position: absolute;
}
</style>
<body>
<button class="new" onclick="newCodeblock()">
New
</button>
<button class="edit" onclick="editCode()">
Edit
</button><br>
<code class="codeblock" id="codeBlock">
<!DOCTYPE html><br>
<html><br>
<head><br>
<meta charset=“UTF-8”><br>
<title>Example</title><br>
</head><br>
<body><br>
<div><br>
<p>This is in a <code> tag</p><br>
</div><br>
</body><br>
</html>
</code><br>
<script>
function editCode() {
var x = document.getElementById('codeBlock');
x.setAttribute("contenteditable", "true")
var y = document.createElement('button')
y.innerHTML = "Cancel";
y.className = "cancel";
document.body.appendChild(y);
y.addEventListener('click', function() {
x.setAttribute("contenteditable", "false")
y.remove()
})
}
function boldText(e) {
if (e.keyCode == 17 && e.keyCode == 66) {
let textBox = document.querySelector('.codeblock');
textBox.style.fontWeight = 'bold';
}
}
function newCodeblock() {
var z = document.createElement('code');
var h = document.createElement('button');
z.className = "codeblock";
z.innerHTML = "Write Here"
z.setAttribute("contenteditable", "true");
h.innerHTML = "Save";
h.addEventListener('click', function() {
z.setAttribute("contenteditable", "false");
h.remove();
})
document.querySelector('.codeblockDiv').appendChild(h);
document.querySelector('.codeblockDiv').appendChild(x);
}
</script>
<div class="codeblockDiv">
</div>
</body>
JSFiddle here
Your newCodeblock function is referencing a non-existent variable x
if you change
document.querySelector('.codeblockDiv').appendChild(x);
to read
document.querySelector('.codeblockDiv').appendChild(z);
Your newCodeblock function will run successfully
I need multiple youtube player inside each .player div, But here only one player is loading with my code.
So can anyone please help me to find where is the problem?
$(document).ready(function(){
var iframeCount = $('.player');
iframeCount.each(function (index) {
$(this).attr('id', 'player-'+index);
});
var player, pId, playerText;
$('.start-video').on('click', function (index) {
onPlayerStateChange = function (event) {
if (event.data == YT.PlayerState.ENDED) {
event.target.destroy();
}
}
playerText = $(this).siblings('.player').text();
pId = $(this).siblings('.player').attr('id');
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
onYouTubeIframeAPIReady = function () {
player = new YT.Player(pId, {
height: '244',
width: '434',
videoId: playerText, // youtube video id
playerVars: {
'autoplay': 1,
'rel': 0,
'showinfo': 0
},
events: {
'onStateChange': onPlayerStateChange
}
});
}
$(this).parent().find('.start-video').fadeOut();
});
});
.y-video{
position: relative;
display: inline-block;
min-width: 434px;
min-height: 262px;
}
.y-video img{
position: absolute;
width: 434px;
height: 244px;
left: 0;
top: 0;
}
.play-icon{
display: inline-block;
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
top: 42%;
z-index: 1;
width: 40px;
font-size: 26px;
border: 3px solid #fff;
border-radius: 50%;
text-align: center;
color: #fff;
padding: 4px 0 4px 5px;
cursor: pointer;
background: rgba(0,0,0,.7);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="y-video">
<div class="player">gpzuVt_mkKs</div>
<span class="play-icon start-video">▷</span>
<img class="start-video" src="http://img.youtube.com/vi/gpzuVt_mkKs/0.jpg">
</div>
<div class="y-video">
<div class="player">Ep6U7vGjFw0</div>
<span class="play-icon start-video">▷</span>
<img class="start-video" src="http://img.youtube.com/vi/Ep6U7vGjFw0/0.jpg">
</div>
<div class="y-video">
<div class="player">6lt2JfJdGSY</div>
<span class="play-icon start-video">▷</span>
<img class="start-video" src="http://img.youtube.com/vi/6lt2JfJdGSY/0.jpg">
</div>
You need to separate the classes of each player (e.g. player1, player2 onwards), this will help your application separate each code/player.
Code snippet from a related SO post:
<div id="ytplayer1"></div>
<div id="ytplayer2"></div>
<script>
var player;
var player2;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer1', {
height: '390',
width: '640',
videoId: 'hdy78ehsjdi'
});
player2 = new YT.Player('ytplayer2', {
height: '390',
width: '640',
videoId: '81hdjskilct'
});
}
</script>
There is also a Github code for playing multiple videos using Youtube API iFrame.
Hope this helps.
Used following reference to fix my issue: [http://jsfiddle.net/KtbYR/5/][1]
$(document).ready(function(){
var iframeCount = $('iframe');
iframeCount.each(function (index) {
$(this).attr('id', 'player-'+index);
});
});
function getFrameID(id) {
var elem = document.getElementById(id);
if (elem) {
if (/^iframe$/i.test(elem.tagName)) return id; //Frame, OK
// else: Look for frame
var elems = elem.getElementsByTagName("iframe");
if (!elems.length) return null; //No iframe found, FAILURE
for (var i = 0; i < elems.length; i++) {
if (/^https?:\/\/(?:www\.)?youtube(?:-nocookie)?\.com(\/|$)/i.test(elems[i].src)) break;
}
elem = elems[i]; //The only, or the best iFrame
if (elem.id) return elem.id; //Existing ID, return it
// else: Create a new ID
do { //Keep postfixing `-frame` until the ID is unique
id += "-frame";
} while (document.getElementById(id));
elem.id = id;
return id;
}
// If no element, return null.
return null;
}
// Define YT_ready function.
var YT_ready = (function() {
var onReady_funcs = [],
api_isReady = false;
/* #param func function Function to execute on ready
* #param func Boolean If true, all qeued functions are executed
* #param b_before Boolean If true, the func will added to the first
position in the queue*/
return function(func, b_before) {
if (func === true) {
api_isReady = true;
for (var i = 0; i < onReady_funcs.length; i++) {
// Removes the first func from the array, and execute func
onReady_funcs.shift()();
}
}
else if (typeof func == "function") {
if (api_isReady) func();
else onReady_funcs[b_before ? "unshift" : "push"](func);
}
}
})();
// This function will be called when the API is fully loaded
function onYouTubePlayerAPIReady() {
YT_ready(true)
}
var players = {};
//Define a player storage object, to enable later function calls,
// without having to create a new class instance again.
YT_ready(function() {
$(".thumb + iframe[id]").each(function() {
var identifier = this.id;
var frameID = getFrameID(identifier);
if (frameID) { //If the frame exists
players[frameID] = new YT.Player(frameID, {
events: {
"onReady": createYTEvent(frameID, identifier)
}
});
}
});
});
// Returns a function to enable multiple events
function createYTEvent(frameID, identifier) {
return function (event) {
var player = players[frameID]; // player object
var the_div = $('#'+identifier).parent();
the_div.children('.thumb').click(function() {
var $this = $(this);
$this.fadeOut().next().addClass('play');
setTimeout(function(){
$this.siblings('.thumb').hide();
},150);
if ($this.next().hasClass('play')) {
player.playVideo();
//player.destroy();
}
});
}
}
// Load YouTube Frame API
(function(){ //Closure, to not leak to the scope
var s = document.createElement("script");
s.src = "http://www.youtube.com/player_api"; /* Load Player API*/
var before = document.getElementsByTagName("script")[0];
before.parentNode.insertBefore(s, before);
})();
.y-video{
position: relative;
display: block;
width: 500px;
clear: left;
}
.play-icon{
display: inline-block;
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
top: 42%;
z-index: 1;
width: 40px;
font-size: 26px;
border: 2px solid #fff;
border-radius: 50%;
text-align: center;
color: rgba(255,255,255,0.4);
padding: 4px 0 4px 5px;
cursor: pointer;
background: rgba(0,0,0,.1);
-webkit-transition: 0.4s;
-moz-transition: 0.4s;
transition: 0.4s;
}
img.thumb{
position: absolute;
width: 100%;
height: auto;
max-height: 281px;
left: 0;
top: 0;
}
.y-video:hover .play-icon{
border-color: rgba(0,0,0,.1);
background: rgba(0,0,0,.6);
color: rgba(255,255,255,0.8);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="y-video">
<span class="thumb play-icon">▷</span>
<img class="thumb" src="http://img.youtube.com/vi/gpzuVt_mkKs/0.jpg">
<iframe width="500" height="281" frameborder="0" src="https://www.youtube.com/embed/gpzuVt_mkKs?enablejsapi=1&showinfo=0&rel=0">
</iframe>
</div>
<div class="y-video">
<span class="thumb play-icon">▷</span>
<img class="thumb" src="http://img.youtube.com/vi/Ep6U7vGjFw0/0.jpg">
<iframe width="500" height="281" frameborder="0" src="https://www.youtube.com/embed/Ep6U7vGjFw0?enablejsapi=1&showinfo=0&rel=0">
</iframe>
</div>
<div class="y-video">
<span class="thumb play-icon">▷</span>
<img class="thumb" src="http://img.youtube.com/vi/6lt2JfJdGSY/0.jpg">
<iframe width="500" height="281" frameborder="0" src="https://www.youtube.com/embed/6lt2JfJdGSY?enablejsapi=1&showinfo=0&rel=0">
</iframe>
</div>
I want make a multiply chating system like facebook. So I collect this script from this webpage
In this script they are passing 2 variable in register_popup function as id and name. Now if I pass any numerical value as id for twice or more, this script not working. But for a new numerical value work well.
So I want to sand my usersID as ID and UserNAME as NAME for further process. How can I solve this? Here is this script:
<a class="content" href="#" id="Aaa" data-name="aaa">AAA</a><br>
<a class="content" href="#" id="1013" data-name="bbb">BBB</a><br>
<a class="content" href="#" id="1014" data-name="ccc">CCC</a>
<script>
$(document).on('click', 'a.content', function() {
var ID = $(this).attr("id");
var NAME = $(this).data("name");
register_popup(ID, NAME);
});
//this function can remove a array element.
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
//this variable represents the total number of popups can be displayed according to the viewport width
var total_popups = 0;
//arrays of popups ids
var popups = [];
//this is used to close a popup
function close_popup(id) {
for (var iii = 0; iii < popups.length; iii++) {
if (id == popups[iii]) {
Array.remove(popups, iii);
document.getElementById(id).style.display = "none";
calculate_popups();
return;
}
}
}
//displays the popups. Displays based on the maximum number of popups that can be displayed on the current viewport width
function display_popups() {
var right = 220;
var iii = 0;
for (iii; iii < total_popups; iii++) {
if (popups[iii] != undefined) {
var element = document.getElementById(popups[iii]);
element.style.right = right + "px";
right = right + 320;
element.style.display = "block";
}
}
for (var jjj = iii; jjj < popups.length; jjj++) {
var element = document.getElementById(popups[jjj]);
element.style.display = "none";
}
}
//creates markup for a new popup. Adds the id to popups array.
function register_popup(id, name) {
for (var iii = 0; iii < popups.length; iii++) {
//already registered. Bring it to front.
if (id == popups[iii]) {
Array.remove(popups, iii);
popups.unshift(id);
calculate_popups();
return;
}
}
var element = '<div class="popup-box chat-popup" id="' + id + '">';
element = element + '<div class="popup-head">';
element = element + '<div class="popup-head-left">' + name + '</div>';
element = element + '<div class="popup-head-right">✕</div>';
element = element + '<div style="clear: both"></div></div><div class="popup-messages"></div></div>';
document.getElementsByTagName("body")[0].innerHTML = document.getElementsByTagName("body")[0].innerHTML + element;
popups.unshift(id);
calculate_popups();
}
//calculate the total number of popups suitable and then populate the toatal_popups variable.
function calculate_popups() {
var width = window.innerWidth;
if (width < 540) {
total_popups = 0;
} else {
width = width - 200;
//320 is width of a single popup box
total_popups = parseInt(width / 320);
}
display_popups();
}
//recalculate when window is loaded and also when window is resized.
window.addEventListener("resize", calculate_popups);
window.addEventListener("load", calculate_popups);
</script>
<style>
#media only screen and (max-width: 540px) {
.chat-sidebar {
display: none !important;
}
.chat-popup {
display: none !important;
}
}
.chat-sidebar {
width: 200px;
position: fixed;
height: 100%;
right: 0px;
top: 0px;
padding-top: 10px;
padding-bottom: 10px;
border: 1px solid rgba(29, 49, 91, .3);
}
.sidebar-name {
padding-left: 10px;
padding-right: 10px;
margin-bottom: 4px;
font-size: 12px;
}
.sidebar-name span {
padding-left: 5px;
}
.sidebar-name a {
display: block;
height: 100%;
text-decoration: none;
color: inherit;
}
.sidebar-name:hover {
background-color: #e1e2e5;
}
.sidebar-name img {
width: 32px;
height: 32px;
vertical-align: middle;
}
.popup-box {
display: none;
position: fixed;
bottom: 0px;
right: 220px;
height: 285px;
background-color: rgb(237, 239, 244);
width: 300px;
border: 1px solid rgba(29, 49, 91, .3);
}
.popup-box .popup-head {
background-color: #6d84b4;
padding: 5px;
color: white;
font-weight: bold;
font-size: 14px;
clear: both;
}
.popup-box .popup-head .popup-head-left {
float: left;
}
.popup-box .popup-head .popup-head-right {
float: right;
opacity: 0.5;
}
.popup-box .popup-head .popup-head-right a {
text-decoration: none;
color: inherit;
}
.popup-box .popup-messages {
height: 100%;
overflow-y: scroll;
}
</style>
You could use ajax call to handle the data.
function sendData() {
$.ajax({
context:this,
type:"POST",
dataType:"json",
data: { ID: userID, NAME: UserNAME },
success: function(response){
//something
},
error: function(errorData){alert(errorData);}
});
The following code initially loads more content when the bottom button is clicked but I need it to work when the scroll reach the bottom of the page... I've tried the code under the words //HERE IS THE PROBLEM// but it seems not to work.... any idea?
var lazyload = lazyload || {};
(function($, lazyload) {
"use strict";
var page = 2,
buttonId = "#button-more",
loadingId = "#loading-div",
container = "#container";
//HERE IS THE PROBLEM
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
lazyload.load = function() {
var url = "./" + page + ".html";
$(buttonId).hide();
$(loadingId).show();
$.ajax({
url: url,
success: function(response) {
if (!response || response.trim() == "NONE") {
$(buttonId).fadeOut();
$(loadingId).text("No more entries to load!");
return;
}
appendContests(response);
},
error: function(response) {
$(loadingId).text("Sorry, there was some error with the request. Please refresh the page.");
}
});
};
}
});
var appendContests = function(response) {
var id = $(buttonId);
$(buttonId).show();
$(loadingId).hide();
$(response).appendTo($(container));
page += 1;
};
})(jQuery, lazyload);
body{
background-color: #ccc;
margin: 0;
}
#wrapper{
width:100%;
margin: 0 auto;
min-height: 500px;
background-color: #e9e9e9;
color: #333;
padding: 10px;
text-align: center;
}
#data-container{
margin: 10px;
}
#data-container .data-item{
background-color: #444444;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
padding: 105px;
margin: 5px;
color: #fff;
}
#loading-div{
display: none;
}
#button-more{
cursor: pointer;
margin: 0 auto;
background-color: #aeaeae;
color: #fff;
width: 200px;
height: 50px;
line-height: 50px;
}
.child{
width:100%;
height:1000px;
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<h1>Lazy Load Demo</h1>
<div id="container">
<div class="child">
</div>
</div>
<div id="button-more" onclick="lazyload.load()">
Load more items
</div>
<div id="loading-div">
loading more items
</div>
</div>
let more = document.querySelector("button");
let show = document.querySelector(".show");
let loading = document.querySelector(".loading");
let bottom = document.querySelector(".bottom");
let allowAjax = true;
function getAjax(){
loading.classList.add("show");
if(allowAjax === true){
allowAjax = false;
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let back = xhttp.response;
back = JSON.parse(back);
let imgSrc = back.results[0].picture.large;
let imgEl = document.createElement("img");
imgEl.src = imgSrc;
show.appendChild(imgEl);
loading.classList.remove("show");
allowAjax = true;
}
};
xhttp.open("GET", "https://randomuser.me/api/", true);
xhttp.send();
}
}
window.addEventListener("scroll",function(){
let scrollPos = window.pageYOffset;
let bottomPos = bottom.offsetTop;
if(bottomPos / 1.5 <= scrollPos){
// Almost to the bottom of the page
getAjax();
}
});
more.addEventListener("click",function(){
getAjax();
});
img{
display: block;
width: 30em;
height: 30em;
}
.more{
position: fixed;
top: 1em;
right: 5em;
background: skyblue;
color: #FFF;
padding: 0.5em;
border: none;
cursor: pointer;
outline: none;
}
.loading{
width: 10em;
height: 10em;
display: none;
position: fixed;
top: 5em;
right: 1em;
background: #212323;
padding: 0.5em;
}
.loading.show{
display: block;
}
.show img{
display: block;
width: 30em;
height: 30em;
}
<img src="https://unsplash.it/300/300/?random" />
<img src="https://unsplash.it/300/300/?random" />
<img src="https://unsplash.it/300/300/?random" />
<img src="https://unsplash.it/300/300/?random" />
<div class="show"></div>
<div class="bottom"></div>
<button class="more">More</button>
<img src="http://www.lettersmarket.com/uploads/lettersmarket/blog/loaders/common_metal/ajax_loader_metal_512.gif"class="loading">
initially loads
I'm creating a modal window bookmarklet that allows you to quickly add content to my website. It all works fine and dandy except for non-html content, because then it cannot append data to the body. Instead, I'd like to do a simple location.href.
Current code:
if (typeof jQuery == 'undefined') {
var jQ = document.createElement('script');
jQ.type = 'text/javascript';
jQ.onload=runthis;
jQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
document.body.appendChild(jQ);
} else {
runthis();
}
function runthis() {
if ($("#baasframe").length == 0) {
$("body").append("\
<div id='baasframe'>\
<div id='baasframe_veil' style=''>\
<p>Loading...</p>\
</div>\
<iframe src='http://example.com/submit.php?url="+encodeURIComponent(location.href)+"&title="+encodeURIComponent(document.title)+"' onload=\"$('#baasframe iframe').slideDown(500);\">Enable iFrames.</iframe>\
<style type='text/css'>\
#baasframe_veil { display: none; position: fixed; width: 100%; height: 100%; top: 0; left: 0; background-color: rgba(0,0,0,.50); cursor: pointer; z-index: 900; }\
#baasframe_veil p { color: white; font: normal normal bold 20px/20px Helvetica, sans-serif; position: absolute; top: 50%; left: 50%; width: 10em; margin: -10px auto 0 -5em; text-align: center; }\
#baasframe iframe { display: none; position: fixed; top: 10%; left: 10%; width: 80%; height: 80%; z-index: 999; border: 10px solid rgba(0,0,0,.5); margin: -5px 0 0 -5px; }\
</style>\
</div>");
$("#baasframe_veil").fadeIn(750);
}
$("#baasframe_veil").click(function(event){
$("#baasframe_veil").fadeOut(750);
$("#baasframe iframe").slideUp(500);
setTimeout("$('#baasframe').remove()", 750);
});
}
function getSelText() {
var s = '';
if (window.getSelection) {
s = window.getSelection();
} else if (document.getSelection) {
s = document.getSelection();
} else if (document.selection) {
s = document.selection.createRange().text;
}
return s;
}
How can I make it detect that the appending of data didn't work and direct it to a location.href instead?
Much obliged,
Dennis
Use document.documentElement.