how to remove previous js file from DOM - javascript

(function() {
setTimeout(function(){
$('#core-notify').remove();
$('#yourDynamicGeneratedScript').remove();
$('#yourDynamicGeneratedScriptHtml').remove();
context = $("#context").val();
lid = $("#userid").val();
tid = $("#tenentId").val();
dp_url = $("#dpUrl").val();
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute('id', 'yourDynamicGeneratedScript');
script_tag.setAttribute("src",
"https://sa.nlpbots.com/lightbot/js/light_bot.js");
(document.getElementsByTagName("head")[0]).appendChild(script_tag);
console.log((document.getElementsByTagName("head")[0]));
},1000);
})();
This code removes a script by tag id but it only removes it from the head tag, not from the DOM file.

Related

Append a generated script after a specific div

Have this code :
<script>
(function()
{
let relScript = document.createElement('script');
relScript.src="https://mountain.com/assets/js/sso.js";
relScript.type  = "text/javascript";
relScript.async  = true;
relScript.defer  = true;
$('.skip-page').append(relScript);
})();
</script>
The script is attached to body and not to this <div class="skip-page">;
My goal is to put this script after the div skip-page; Any ideas why is append to body ?
using load event
// not use JQuery
window.onload = function (){
let relScript = document.createElement('script');
relScript.src="https://mountain.com/assets/js/sso.js";
relScript.type = "text/javascript";
relScript.async = true;
relScript.defer = true;
$('.skip-page').append(relScript);
};
// Using JQuery
$(function(){
let relScript = document.createElement('script');
relScript.src="https://mountain.com/assets/js/sso.js";
relScript.type = "text/javascript";
relScript.async = true;
relScript.defer = true;
$('.skip-page').append(relScript);
});

Bookmarklet to briefly flash a message

Trying to develop a Bookmarklet to copy contents of a specific field on webpage AND then briefly flash a confirmation message. Already have both parts working separately. Can't figure out how to combine them to be able to then put that code into URL field of Bookmarklet.
javascript: (function(){var copyText = document.getElementById("mergeFields-input-text");copyText.select();document.execCommand("Copy");
function tempAlert(msg,duration)
{
var el = document.createElement("div");
el.setAttribute("style","position:absolute;top:5%;left:20%;background-color:white;");
el.innerHTML = msg;
setTimeout(function(){
el.parentNode.removeChild(el);
},duration);
document.body.appendChild(el);
}
var d = document.getElementById('mergeFields-input-text');
d.onclick = function(){ tempAlert("Copied",5000); })();
No need to add the 'onclick' event. Try this bookmarklet:
javascript:(function() {
var copyText = document.getElementById("mergeFields-input-text");
copyText.select();
document.execCommand("Copy");
tempAlert("Copied", 5000);
function tempAlert(msg, duration) {
var el = document.createElement("div");
el.setAttribute("style","position:absolute;top:5%;left:20%;background-color:white;");
el.innerHTML = msg;
document.body.appendChild(el);
setTimeout(function(){
el.parentNode.removeChild(el);
}, duration
);
}
})();
Above code from Shugar answers my question for copying, and this code below, also from him, does same except pasting:
javascript:(function() {
var pasteText = document.getElementById("mergeFields-input-text").select();
document.execCommand("Paste");
tempAlert("PASTED SUBJECT", 500);
function tempAlert(msg, duration) {
var el = document.createElement("div");
el.setAttribute("style","position:absolute;top:2%;left:45%;background-color:yellow;");
el.innerHTML = msg;
document.body.appendChild(el);
setTimeout(function(){
el.parentNode.removeChild(el);
}, duration
);
}
})();

jQuery tabs working on some but not all websites

I am attempting to create a tabbed form that will work across several websites. I have found that the code snippet works on some pages, and the tabs exist and function properly, but on one particular website the tabs do not display and I get the following console error: Uncaught TypeError: $(...).tabs is not a function. I have not had any luck debugging this myself or searching for answers online. Any help would be appreciated :)
Website I have issues with: http://www.jetstar.com/sg/en/home
Website it appears to work fine on: https://tigerair.com.au/
Note that the code snippet below assumes jQuery does exist on the website already. I have tried loading the latest version of jQuery first also with no luck.
if (typeof($) == 'undefined') {
var $ = jQuery;
}
function createInvisibleDiv() {
var invisiblePageSizedDiv = document.createElement("div");
invisiblePageSizedDiv.setAttribute("id", "pageDiv");
invisiblePageSizedDiv.setAttribute("class", "overlay");
document.body.appendChild(invisiblePageSizedDiv);
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.overlay{bottom:0; right:0; left: 0; top:0; overflow:hidden;background-color:rgba(88,88,90,0.8); z-index: 100; position:absolute;}';
document.body.appendChild(style);
document.body.style.position = "relative";
}
//this function creates the two tabs
function createUnorderedList(){
var $unorderedList = $("<ul></ul>");
$unorderedList.attr("id", "unorderedList");
$unorderedList.attr("class", "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all")
for (var i=1; i<3; ++i) {
var $linkItem = $("<li></li>");
$linkItem.append(createLink(i));
$linkItem.attr("class", "ui-state-default ui-corner-top")
$unorderedList.append($linkItem);
}
return $unorderedList;
}
function createLink(i){
var $link = $("<a></a>");
if (i==1) {
$link.attr({"href":'#foo', "title":"Foo"});
$link.text("Foo");
} else {
$link.attr({"href":'#bar', "title":"Bar"});
$link.text("Bar");
}
return $link;
}
function createFooForm() {
var $ele = $("<div></div>");
$ele.attr("id", "foo");
$ele.text("Thanks for looking at my code");
return $ele;
}
function createBarForm() {
var $ele = $("<div></div>");
$ele.attr("id", "bar");
$ele.text("I super appreciate it!");
return $ele;
}
function loadScript(url, callback)
{
// Adding the script tag to the head
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}
var generateTabsFunction = function() {
createInvisibleDiv();
var $invisibleDiv = $('#pageDiv');
var $containerDiv = $("<div></div>");
$containerDiv.attr("id", "containerDiv");
$containerDiv.append(createUnorderedList());
$containerDiv.append(createFooForm());
$containerDiv.append(createBarForm());
$invisibleDiv.append($containerDiv);
$('body').append($containerDiv);
$( "#containerDiv" ).tabs();
}
$("<link/>", {
rel: "stylesheet",
type: "text/css",
href: "https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"
}).appendTo("head");
loadScript("https://code.jquery.com/ui/1.12.1/jquery-ui.js", generateTabsFunction);
Sounds like you have included JQuery, but forgot to include JQueryUI

Binding YouTube Video to Div Element from Seperate JS file

I have this problem embedding YouTube video in a PhoneJS single-page mobile application. In PhoneJS, the JS scripts are defined in a different file. So I defined the HTML div like this:
<div id="player"></div>
Now in the JS file, I did this:
function getVideo() {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var playerDiv = document.getElementById('player');
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player(playerDiv, {
height: '250',
width: '444',
videoId: sIFYPQjYhv8
});
}
}
When I run and view the debugger, the call is made to Youtube and response is received, but it is not displayed on the view.
Ok since I am using KnockoutJS binding, I modified the div in the html view like this:
<iframe id="player" type="text/html" width="444" height="250" frameborder="0" data-bind="attr: { src: src }"></iframe>
And then pass in the src video id thus:
src: ko.observable('http://www.youtube.com/embed/' + sIFYPQjYhv8 + '?autoplay=1')
In this case however, in the debugger, the call is not even made to Youtube. Nothing just happens. Actually I prefer to use the API call instead of the second approach.
Any suggestions on how to make the first approach work? I mean using the API call?
EDIT
Just want to mention that when I add the code below in the view, the video is streamed alright.
<h1>Video</h1>
<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var playerDiv = document.getElementById('player');
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player(playerDiv, {
height: '250',
width: '444',
videoId: 'sIFYPQjYhv8'
});
}
</script>
I think the easiest way to do this is to use a custom binding handler with a flag set from the onYouTubeIFrameAPIReady callback
Sample jsFiddle
ko.bindingHandlers['player'] = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// Check if global script and function is declared.
if ( !document.getElementById('playerScript') ) {
// Create script
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var playerDiv = document.getElementById('player');
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Create global function that their API calls back
window.playerReady = ko.observable(false);
window.onYouTubeIframeAPIReady = function() {
window.playerReady(true);
};
}
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var value = valueAccessor(),
id = value.id(),
height = ko.unwrap(value.height) || '250',
width = ko.unwrap(value.width) || '444'
;
if ( !value.id()) {
return;
}
if ( !window.playerReady() ) {
// YT hasn't invoked global callback. Subscribe to update
var subscription;
subscription = window.playerReady.subscribe( function(newValue) {
if ( newValue ) {
subscription.dispose();
// Just get this binding to fire again
value.id.notifySubscribers(value.id());
}
});
} else {
var player = new YT.Player( element, {
height: height,
width: width,
videoId: id
});
}
},
}
Now change your player div to
<div data-bind="player: { id: id, height: height, width: width }"></div>
Finally bind
var vm = {
id: 'sIFYPQjYhv8',
height: '250',
width: '444'
};
ko.applyBindings( vm )
EDIT
To remove the reliance on window, put your script tag that adds the new script element back, tweek as below, modify their callback and use a setTimeout instead of the "playerReady" observable
HTML Script
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
tag.setAttribute('id', 'playerScript');
tag.setAttribute('data-ready', 'false');
...
function onYouTubeIframeAPIReady = function() {
document.getElementById('playerScript').setAttribute('data-ready', 'true');
};
Player Binding
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var value = valueAccessor(),
id = value.id(),
height = ko.unwrap(value.height) || '250',
width = ko.unwrap(value.width) || '444',
playerScript = document.getElementById('playerScript')
;
if ( !value.id()) {
return;
}
if ( !playerScript || playerScript.getAttribute('data-ready') !== 'true' ) ) {
// YT hasn't invoked global callback.
setTimeout( function() {
value.id.notifySubscribers(value.id());
}, 50);
} else {
var player = new YT.Player( element, {
height: height,
width: width,
videoId: id
});
}
}

Document.body in Opera

I've got a problem with retrieving link to the body tag. I've tried:
document.body, unfortunately it is null
search body by tagName while enumerating childs of document, it's found only the head tag :(
document.getElementsByTagName, return undefined
I'm trying to get link to the body tag in onload event handler. This is a HTML code of the page:
<html>
<head>
<title>Some page</title>
<script src="/adv.js" type="text/javascript"></script>
</head>
<body>
This is text
</body>
</html>
Here the source code of adv.js:
(function () {
var myRandom = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
var myFunction = function () {
var newScriptAddr = '/adLoader.js?r=' + myRandom(1,1000000);
var fileref = document.createElement('script');
if (typeof fileref != "undefined")
{
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", newScriptAddr);
document.getElementsByTagName("head")[0].appendChild(fileref);
}
};
if (window.onload)
{
var currOnLoad = window.onload;
window.onload = function () {
currOnLoad();
myFunction();
};
}
else
window.onload = myFunction();
}) ();
Source code of adLoader.js:
(function () {
var mainCnt = document.createElement('div');
mainCnt.appendChild(document.createTextNode('The text'));
var _body = document.body;
if (!_body)
{
var htmlTag = document.documentElement;
for(var i = 0; i < htmlTag.childNodes.length; i++)
{
if (htmlTag.childNodes[i].nodeName.toLowerCase() == 'body')
{
_body = htmlTag.childNodes[i];
break;
}
}
}
if (!_body)
_body = document.getElementsByTagName('BODY') [0];
if (!_body)
_body = document.getElementsByTagName('body') [0];
if (_body)
_body.appendChild(mainCnt);
else
alert('WTF!!');
}) ();
Browser is Opera 11.10 OS Ubuntu Linux. Is there way to get this link? My aim is to add div with position:fixed to the body tag.
myFunction() doesn't return a function, so you are assigning undefined to window.onload. You probably mean window.onload = myFunction;
Anyway, as written at the moment, the code runs immediately and the body element hasn't been reached.
if the js code in head tag and the query the body tag before onload event, null should be got while browser just reading the head.

Categories

Resources