Ok! I'm working on a wordpress site, and everything this javascript add on is supposed to do, it does...But, when I inspect element via safari develop, I notice that it's loading all of my headers scripts,meta,styles etc. into the body as well as the head. I can't figure out why. Here's what the script looks like:
function ft(params) {
var ol= document.addEventListener?"DOMContentLoaded":"load"; //on load event
var navB = params.navB || "reverse slide"; //backbrowser button effect, default empty
var but = params.but || false; //Allow transitions on input type button
var cBa = params.cBa || function() {};
function aDL(url, t, o) { //Ajax Div Load
if (window.XMLHttpRequest) {
r = new XMLHttpRequest();
} else if (window.ActiveXObject) {
r = new ActiveXObject("Microsoft.XMLHTTP");
}
if (r != undefined) {
r.onreadystatechange = function() {Ol(r, t, o);};
r.open("GET", url, true);
r.send("");
}
}
function Ol(r, t, o) { //On load div
if (r.readyState == 4) {
if (r.status == 200 || r.status == 0) {
t.innerHTML = r.responseText;
o();
} else {
t.innerHTML="Error:\n"+ r.status + "\n" +r.statusText;
}
}
}
function DE() //Div Effect
{
var dochtml = document.body.innerHTML;
document.body.innerHTML = "";
var d1 = document.createElement("div");
d1.id = "d1";
d1.style.zIndex = 2;
d1.style.position = "absolute";
d1.style.width = "100%";
d1.style.height = "100%";
d1.style.left = "0px";
d1.style.top = "0px";
document.body.appendChild(d1);
d1.innerHTML = dochtml;
var d2 = document.createElement("div");
d2.id = "d2";
d2.style.zIndex = 1;
d2.style.position = "absolute";
d2.style.width = "100%";
d2.style.height = "100%";
d2.style.left = "0px";
d2.style.top = "0px";
document.body.appendChild(d2);
return {d1: d1, d2: d2 };
}
function timeOuts(e, d1,d2)
{
setTimeout(function() { d1.className = e + " out"; }, 1);
setTimeout(function() { d2.className = e + " in"; }, 1);
setTimeout(function() {
document.body.innerHTML = d2.innerHTML;
cBa();
}, 706);
}
function slideTo(href, effect, pushstate)
{
var d = DE();
var d1 = d.d1;
var d2 = d.d2;
aDL(href, d2,
function() {
if (pushstate && window.history.pushState) window.history.pushState("", "", href);
timeOuts(effect,d1,d2);
}
);
}
function dC(e){ //Detect click event
var o;
var o=e.srcElement || e.target;
var tn = o.tagName.toLowerCase();
if (!but || tn!="input" || o.getAttribute("type")!="button") //if it is not a button
{
//try to find an anchor parent
while (tn!=="a" && tn!=="body")
{
o = o.parentNode;
tn = o.tagName.toLowerCase();
}
if (tn==="body") return;
}
var t = o.getAttribute("data-ftrans");
if (t)
{
e.preventDefault();
var hr = o.getAttribute("href") || o.getAttribute("data-href");
if (hr) slideTo(hr, t, true);
}
}
function aE(ev, el, f) { //Add event
if (el.addEventListener) // W3C DOM
el.addEventListener(ev,f,false);
else if (el.attachEvent) { // IE DOM
var r = el.attachEvent("on"+ev, f);
return r;
}
}
aE("click", window, dC);
aE(ol, document, //On load
function(ev)
{
aE("popstate", window, function(e) { //function to reload when back button is clicked
slideTo(location.pathname, navB, false);
});
}
);
}
here is the link to the site: http://www.fasw.ws/faswwp/non-jquery-page-transitions-lightweight/
I assume that thats not supposed to happen. So im trying to figure out how to keep it clean, and keep the head files loaded in the head, and only load the page content. I cannot figure this one out, some help from the pros is needed :)
FASW comes with two functions that serves as "hooks" both before and after initializing the component. you can do it like this:
(function inittrans()
{
initComponents();
var params = { /*put your options here*/ };
new ft(params);
})();
function onTransitionFinished()
{
initComponents();
}
function initComponents() {
// here is where you put your "other" javascript codes
}
Notice how your javascript codes are executed after loading your initial page and once again after the transition happened. Anyway, this is how I got the work around on it 'coz javascript codes just won't work as they are loaded by FASW via Ajax on-the-fly.
Related
I am appending dynamic DOM elements (after Ajax calls to gather the data) as seen below. I have narrowed the code down to what I believe is most important:
<!-- SideMenu HTML -->
<div id="sidebar-menu">
<ul id="folders">
<!-- AJAX DATA POPULATES MENU HERE -->
<!-- HTML File calling JS function -->
<script>
$(document).ready(function() {
getParentFolders('parentFolderTitle');
});
</script>
// JS File function...
var parentFolders; // Values retrieved from AJAX calls
function buildFolderMenu(index) {
var markup = '<li class="has_sub">' +
'<a ... > parentFolders[index].Name + '</a>' +
'<ul ...>' +
'<li> SUB FOLDER TEST <li>' +
'</ul>' +
'</li>';
$(#folders').append(markup);
}
EDIT: My code is interacting with a 3rd party template, after reading the replies, I was able to track down the file which handles the 'click events'. However, based on my own code shown above, I am not sure how to adjust the template code to work with my dynamically appended DOM.
Here is the template code handling the click: (I can see the 'menuItemClick' function is where this is likely handled, but how do I apply the '.on('', function())' adjustments here, based on how this file is written?)
/**
* Theme: Adminto Admin Template
* Author: Coderthemes
* Module/App: Main Js
*/
!function($) {
"use strict";
var Sidemenu = function() {
this.$body = $("body"),
this.$openLeftBtn = $(".open-left"),
this.$menuItem = $("#sidebar-menu a")
};
Sidemenu.prototype.openLeftBar = function() {
$("#wrapper").toggleClass("enlarged");
$("#wrapper").addClass("forced");
if($("#wrapper").hasClass("enlarged") && $("body").hasClass("fixed-left")) {
$("body").removeClass("fixed-left").addClass("fixed-left-void");
} else if(!$("#wrapper").hasClass("enlarged") && $("body").hasClass("fixed-left-void")) {
$("body").removeClass("fixed-left-void").addClass("fixed-left");
}
if($("#wrapper").hasClass("enlarged")) {
$(".left ul").removeAttr("style");
} else {
$(".subdrop").siblings("ul:first").show();
}
toggle_slimscroll(".slimscrollleft");
$("body").trigger("resize");
},
//menu item click
Sidemenu.prototype.menuItemClick = function(e) {
if(!$("#wrapper").hasClass("enlarged")){
if($(this).parent().hasClass("has_sub")) {
}
if(!$(this).hasClass("subdrop")) {
// hide any open menus and remove all other classes
$("ul",$(this).parents("ul:first")).slideUp(350);
$("a",$(this).parents("ul:first")).removeClass("subdrop");
$("#sidebar-menu .pull-right i").removeClass("md-remove").addClass("md-add");
// open our new menu and add the open class
$(this).next("ul").slideDown(350);
$(this).addClass("subdrop");
$(".pull-right i",$(this).parents(".has_sub:last")).removeClass("md-add").addClass("md-remove");
$(".pull-right i",$(this).siblings("ul")).removeClass("md-remove").addClass("md-add");
}else if($(this).hasClass("subdrop")) {
$(this).removeClass("subdrop");
$(this).next("ul").slideUp(350);
$(".pull-right i",$(this).parent()).removeClass("md-remove").addClass("md-add");
}
}
},
//init sidemenu
Sidemenu.prototype.init = function() {
var $this = this;
var ua = navigator.userAgent,
event = (ua.match(/iP/i)) ? "touchstart" : "click";
//bind on click
this.$openLeftBtn.on(event, function(e) {
e.stopPropagation();
$this.openLeftBar();
});
// LEFT SIDE MAIN NAVIGATION
$this.$menuItem.on(event, $this.menuItemClick);
// NAVIGATION HIGHLIGHT & OPEN PARENT
$("#sidebar-menu ul li.has_sub a.active").parents("li:last").children("a:first").addClass("active").trigger("click");
},
//init Sidemenu
$.Sidemenu = new Sidemenu, $.Sidemenu.Constructor = Sidemenu
}(window.jQuery),
function($) {
"use strict";
var FullScreen = function() {
this.$body = $("body"),
this.$fullscreenBtn = $("#btn-fullscreen")
};
//turn on full screen
// Thanks to http://davidwalsh.name/fullscreen
FullScreen.prototype.launchFullscreen = function(element) {
if(element.requestFullscreen) {
element.requestFullscreen();
} else if(element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if(element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if(element.msRequestFullscreen) {
element.msRequestFullscreen();
}
},
FullScreen.prototype.exitFullscreen = function() {
if(document.exitFullscreen) {
document.exitFullscreen();
} else if(document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if(document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
},
//toggle screen
FullScreen.prototype.toggle_fullscreen = function() {
var $this = this;
var fullscreenEnabled = document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled;
if(fullscreenEnabled) {
if(!document.fullscreenElement && !document.mozFullScreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) {
$this.launchFullscreen(document.documentElement);
} else{
$this.exitFullscreen();
}
}
},
//init sidemenu
FullScreen.prototype.init = function() {
var $this = this;
//bind
$this.$fullscreenBtn.on('click', function() {
$this.toggle_fullscreen();
});
},
//init FullScreen
$.FullScreen = new FullScreen, $.FullScreen.Constructor = FullScreen
}(window.jQuery),
//main app module
function($) {
"use strict";
var App = function() {
this.VERSION = "1.5.0",
this.AUTHOR = "Coderthemes",
this.SUPPORT = "coderthemes#gmail.com",
this.pageScrollElement = "html, body",
this.$body = $("body")
};
//on doc load
App.prototype.onDocReady = function(e) {
FastClick.attach(document.body);
resizefunc.push("initscrolls");
resizefunc.push("changeptype");
$('.animate-number').each(function(){
$(this).animateNumbers($(this).attr("data-value"), true, parseInt($(this).attr("data-duration")));
});
//RUN RESIZE ITEMS
$(window).resize(debounce(resizeitems,100));
$("body").trigger("resize");
// right side-bar toggle
$('.right-bar-toggle').on('click', function(e){
$('#wrapper').toggleClass('right-bar-enabled');
});
},
//initilizing
App.prototype.init = function() {
var $this = this;
//document load initialization
$(document).ready($this.onDocReady);
//init side bar - left
$.Sidemenu.init();
//init fullscreen
$.FullScreen.init();
},
$.App = new App, $.App.Constructor = App
}(window.jQuery),
//initializing main application module
function($) {
"use strict";
$.App.init();
}(window.jQuery);
/* ------------ some utility functions ----------------------- */
//this full screen
var toggle_fullscreen = function () {
}
function executeFunctionByName(functionName, context /*, args */) {
var args = [].slice.call(arguments).splice(2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(this, args);
}
var w,h,dw,dh;
var changeptype = function(){
w = $(window).width();
h = $(window).height();
dw = $(document).width();
dh = $(document).height();
if(jQuery.browser.mobile === true){
$("body").addClass("mobile").removeClass("fixed-left");
}
if(!$("#wrapper").hasClass("forced")){
if(w > 990){
$("body").removeClass("smallscreen").addClass("widescreen");
$("#wrapper").removeClass("enlarged");
}else{
$("body").removeClass("widescreen").addClass("smallscreen");
$("#wrapper").addClass("enlarged");
$(".left ul").removeAttr("style");
}
if($("#wrapper").hasClass("enlarged") && $("body").hasClass("fixed-left")){
$("body").removeClass("fixed-left").addClass("fixed-left-void");
}else if(!$("#wrapper").hasClass("enlarged") && $("body").hasClass("fixed-left-void")){
$("body").removeClass("fixed-left-void").addClass("fixed-left");
}
}
toggle_slimscroll(".slimscrollleft");
}
var debounce = function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(context, args);
return result;
};
}
function resizeitems(){
if($.isArray(resizefunc)){
for (i = 0; i < resizefunc.length; i++) {
window[resizefunc[i]]();
}
}
}
function initscrolls(){
if(jQuery.browser.mobile !== true){
//SLIM SCROLL
$('.slimscroller').slimscroll({
height: 'auto',
size: "7px"
});
$('.slimscrollleft').slimScroll({
height: 'auto',
position: 'right',
size: "7px",
color: '#828e94',
wheelStep: 5
});
}
}
function toggle_slimscroll(item){
if($("#wrapper").hasClass("enlarged")){
$(item).css("overflow","inherit").parent().css("overflow","inherit");
$(item). siblings(".slimScrollBar").css("visibility","hidden");
}else{
$(item).css("overflow","hidden").parent().css("overflow","hidden");
$(item). siblings(".slimScrollBar").css("visibility","visible");
}
}
// === following js will activate the menu in left side bar based on url ====
$(document).ready(function() {
$("#sidebar-menu a").each(function() {
var pageUrl = window.location.href.split(/[?#]/)[0];
if (this.href == pageUrl) {
$(this).addClass("active");
$(this).parent().addClass("active"); // add active to li of the current link
$(this).parent().parent().prev().addClass("active"); // add active class to an anchor
$(this).parent().parent().prev().click(); // click the item to make it drop
}
});
});
var resizefunc = [];
This could because of the redraw event not firing on the browser implicitly after your DOM manipulation. Refer this post on how to redraw so your generated DOM is refreshed on the UI
Force DOM redraw/refresh on Chrome/Mac
If this doesn't work please share your CSS and the before DOM and after DOM generation screenshot
I'm trying to manage to apply an generated image of an audio graph for every div that a music url is found with a Google Chrome Extension.
However, the process of downloading the music from the url and processing the image, takes enough time that all of the images keep applying to the last div.
I'm trying to apply the images to each div as throughout the JQuery's each request. All the div's have the /renderload.gif gif playing, but only the last div flashes as the images finished processing one by one.
Example being that the src is being set to /renderload.gif for all 1,2,3,4,5
but once the sound blob was downloaded and image was generated, only 4-5 gets the images and it continues on loading the queue, repeating the issue.
Here's an example of what I'm trying to deal with.
Here's my latest attempts to add queueing to avoid lag by loading all the audios at once, but it seems the issue still persists.
// context.js
function Queue(){
var queue = [];
var offset = 0;
this.getLength = function(){
return (queue.length - offset);
}
this.isEmpty = function(){
return (queue.length == 0);
}
this.setEmpty = function(){
queue = [];
return true;
}
this.enqueue = function(item){
queue.push(item);
}
this.dequeue = function(){
if (queue.length == 0) return undefined;
var item = queue[offset];
if (++ offset * 2 >= queue.length){
queue = queue.slice(offset);
offset = 0;
}
return item;
}
this.peek = function(){
return (queue.length > 0 ? queue[offset] : undefined);
}
}
var audioqueue=new Queue();
var init=0;
var current=0;
var finished=0;
function RunGraphs(x) {
if (x==init) {
if (audioqueue.isEmpty()==false) {
current++;
var das=audioqueue.dequeue();
var divparent=das.find(".original-image");
var songurl=das.find(".Mpcs").find('span').attr("data-url");
console.log("is song url "+songurl);
console.log("is data here "+divparent.attr("title"));
divparent.css('width','110px');
divparent.attr('src','https://i.pinimg.com/originals/a4/f2/cb/a4f2cb80ff2ae2772e80bf30e9d78d4c.gif');
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET",songurl,true);
xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
xhr.onload = function() {
blob = xhr.response;//xhr.response is now a blob object
console.log(blob);
SCWFRobloxAudioTool.generate(blob, {
canvas_width: 110,
canvas_height: 110,
bar_width: 1,
bar_gap : .2,
wave_color: "#ecb440",
download: false,
onComplete: function(png, pixels) {
if (init == x) {
divparent.attr('src',png);
finished++;
}
}
});
}
xhr.send();
OnHold(x);
}
}
}
function OnHold(x) {
if (x==init) {
if (current > finished+7) {
setTimeout(function(){
OnHold(x)
},150)
} else {
RunGraphs(x)
}
}
}
if (window.location.href.includes("/lib?Ct=DevOnly")){
functionlist=[];
current=0;
finished=0;
init++;
audioqueue.setEmpty();
$(".CATinner").each(function(index) {
(function(x){
audioqueue.enqueue(x);
}($(this)));
});
RunGraphs(init);
};
The SCWFAudioTool is from this github repository.
Soundcloud Waveform Generator
The Queue.js from a search request, slightly modified to have setEmpty support.Queue.js
Please read the edit part of the post
I mad a usable minimal example of your code in order to check your Queue and defer method. there seems to be no error that i can find (i don't have the html file and cant check for missing files. Please do that yourself by adding the if (this.status >= 200 && this.status < 400) check to the onload callback):
// context.js
function Queue(){
var queue = [];
var offset = 0;
this.getLength = function(){
return (queue.length - offset);
}
this.isEmpty = function(){
return (queue.length == 0);
}
this.setEmpty = function(){
queue = [];
return true;
}
this.enqueue = function(item){
queue.push(item);
}
this.dequeue = function(){
if (queue.length == 0) return undefined;
var item = queue[offset];
if (++ offset * 2 >= queue.length){
queue = queue.slice(offset);
offset = 0;
}
return item;
}
this.peek = function(){
return (queue.length > 0 ? queue[offset] : undefined);
}
}
var audioqueue=new Queue();
var init=0;
var current=0;
var finished=0;
function RunGraphs(x) {
if (x==init) {
if (audioqueue.isEmpty()==false) {
current++;
var songurl = audioqueue.dequeue();
console.log("is song url "+songurl);
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET",songurl,true);
xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
xhr.onload = function() {
if (this.status >= 200 && this.status < 400) {
blob = xhr.response;//xhr.response is now a blob object
console.log('OK');
finished++;
} else {
console.log('FAIL');
}
}
xhr.send();
OnHold(x);
}
}
}
function OnHold(x) {
if (x==init) {
if (current > finished+7) {
setTimeout(function(){
OnHold(x)
},150)
} else {
RunGraphs(x)
}
}
}
var demoObject = new Blob(["0".repeat(1024*1024*2)]); // 2MB Blob
var demoObjectURL = URL.createObjectURL(demoObject);
if (true){
functionlist=[];
current=0;
finished=0;
init++;
audioqueue.setEmpty();
for(var i = 0; i < 20; i++)
audioqueue.enqueue(demoObjectURL);
RunGraphs(init);
};
Therefore if there are no errors left concerning missing files the only errors i can think off is related to the SCWFRobloxAudioTool.generate method.
Please check if the callback gets triggered correctly and that no errors accrue during conversion.
If you provide additional additional info, data or code i can look into this problem.
EDIT:
I looked into the 'SoundCloudWaveform' program and i think i see the problem:
The module is not made to handle multiple queries at once (there is only one global setting object. So every attempt to add another query to the api will override the callback of the previous one, and since the fileReader is a async call only the latest added callback will be executed.)
Please consider using an oop attempt of this api:
window.AudioContext = window.AudioContext || window.webkitAudioContext;
Array.prototype.max = function() {
return Math.max.apply(null, this);
};
function SoundCloudWaveform (){
this.settings = {
canvas_width: 453,
canvas_height: 66,
bar_width: 3,
bar_gap : 0.2,
wave_color: "#666",
download: false,
onComplete: function(png, pixels) {}
}
this.generate = function(file, options) {
// preparing canvas
this.settings.canvas = document.createElement('canvas');
this.settings.context = this.settings.canvas.getContext('2d');
this.settings.canvas.width = (options.canvas_width !== undefined) ? parseInt(options.canvas_width) : this.settings.canvas_width;
this.settings.canvas.height = (options.canvas_height !== undefined) ? parseInt(options.canvas_height) : this.settings.canvas_height;
// setting fill color
this.settings.wave_color = (options.wave_color !== undefined) ? options.wave_color : this.settings.wave_color;
// setting bars width and gap
this.settings.bar_width = (options.bar_width !== undefined) ? parseInt(options.bar_width) : this.settings.bar_width;
this.settings.bar_gap = (options.bar_gap !== undefined) ? parseFloat(options.bar_gap) : this.settings.bar_gap;
this.settings.download = (options.download !== undefined) ? options.download : this.settings.download;
this.settings.onComplete = (options.onComplete !== undefined) ? options.onComplete : this.settings.onComplete;
// read file buffer
var reader = new FileReader();
var _this = this;
reader.onload = function(event) {
var audioContext = new AudioContext()
audioContext.decodeAudioData(event.target.result, function(buffer) {
audioContext.close();
_this.extractBuffer(buffer);
});
};
reader.readAsArrayBuffer(file);
}
this.extractBuffer = function(buffer) {
buffer = buffer.getChannelData(0);
var sections = this.settings.canvas.width;
var len = Math.floor(buffer.length / sections);
var maxHeight = this.settings.canvas.height;
var vals = [];
for (var i = 0; i < sections; i += this.settings.bar_width) {
vals.push(this.bufferMeasure(i * len, len, buffer) * 10000);
}
for (var j = 0; j < sections; j += this.settings.bar_width) {
var scale = maxHeight / vals.max();
var val = this.bufferMeasure(j * len, len, buffer) * 10000;
val *= scale;
val += 1;
this.drawBar(j, val);
}
if (this.settings.download) {
this.generateImage();
}
this.settings.onComplete(this.settings.canvas.toDataURL('image/png'), this.settings.context.getImageData(0, 0, this.settings.canvas.width, this.settings.canvas.height));
// clear canvas for redrawing
this.settings.context.clearRect(0, 0, this.settings.canvas.width, this.settings.canvas.height);
},
this.bufferMeasure = function(position, length, data) {
var sum = 0.0;
for (var i = position; i <= (position + length) - 1; i++) {
sum += Math.pow(data[i], 2);
}
return Math.sqrt(sum / data.length);
},
this.drawBar = function(i, h) {
this.settings.context.fillStyle = this.settings.wave_color;
var w = this.settings.bar_width;
if (this.settings.bar_gap !== 0) {
w *= Math.abs(1 - this.settings.bar_gap);
}
var x = i + (w / 2),
y = this.settings.canvas.height - h;
this.settings.context.fillRect(x, y, w, h);
},
this.generateImage = function() {
var image = this.settings.canvas.toDataURL('image/png');
var link = document.createElement('a');
link.href = image;
link.setAttribute('download', '');
link.click();
}
}
console.log(new SoundCloudWaveform());
Also consider simply using an array for the queue:
function Queue(){
var queue = [];
var offset = 0;
this.getLength = function(){
return (queue.length - offset);
}
this.isEmpty = function(){
return (queue.length == 0);
}
this.setEmpty = function(){
queue = [];
return true;
}
this.enqueue = function(item){
queue.push(item);
}
this.dequeue = function(){
if (queue.length == 0) return undefined;
var item = queue[offset];
if (++ offset * 2 >= queue.length){
queue = queue.slice(offset);
offset = 0;
}
return item;
}
this.peek = function(){
return (queue.length > 0 ? queue[offset] : undefined);
}
}
var q = new Queue();
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
console.log(q.dequeue());
console.log(q.dequeue());
console.log(q.dequeue());
console.log(q.dequeue());
var q2 = [];
q2.push(1)
q2.push(2)
q2.push(3)
console.log(q2.shift());
console.log(q2.shift());
console.log(q2.shift());
console.log(q2.shift());
It prevents confusion ant the speedup of it is minimal in your application.
On your open method on the xhr object, set the parameter to true, also... try using the onload() instead of onloadend(). Good Luck!
var xmlhttp = new XMLHttpRequest(),
method = 'GET',
url = 'https://developer.mozilla.org/';
xmlhttp.open(method, url, true);
xmlhttp.onload = function () {
// Do something with the retrieved data
};
xmlhttp.send();
I'm searching on google but i can't find a good solution. I'm searching a pop under script which open a new url window but only once time per seesion. i found a lot of script but the open a new window just for the onclick ...
<script>
function jsPopunder(sUrl, sConfig) {
sConfig = (sConfig || {});
var sName = (sConfig.name || Math.floor((Math.random()*1000)+1));
var sWidth = (sConfig.width || window.innerWidth);
var sHeight = (sConfig.height || window.innerHeight);
var sPosX = (typeof(sConfig.left)!= 'undefined') ? sConfig.left.toString() : window.screenX;
var sPosY = (typeof(sConfig.top) != 'undefined') ? sConfig.top.toString() : window.screenY;
/* capping */
var sWait = (sConfig.wait || 3600); sWait = (sWait*1000);
var sCap = (sConfig.cap || 2);
/* cookie stuff */
var popsToday = 0;
var cookie = (sConfig.cookie || '__.popunder');
var browser = function() {
var n = navigator.userAgent.toLowerCase();
var b = {
webkit: /webkit/.test(n),
mozilla: (/mozilla/.test(n)) && (!/(compatible|webkit)/.test(n)),
chrome: /chrome/.test(n),
msie: (/msie/.test(n)) && (!/opera/.test(n)),
firefox: /firefox/.test(n),
safari: (/safari/.test(n) && !(/chrome/.test(n))),
opera: /opera/.test(n)
};
b.version = (b.safari) ? (n.match(/.+(?:ri)[\/: ]([\d.]+)/) || [])[1] : (n.match(/.+(?:ox|me|ra|ie)[\/: ]([\d.]+)/) || [])[1];
return b;
}();
function isCapped() {
try {
popsToday = Math.floor(document.cookie.split(cookie+'Cap=')[1].split(';')[0]);
} catch(err){}
return (sCap<=popsToday || document.cookie.indexOf(cookie+'=') !== -1);
}
function openIt(sUrl, sName, sOptions) {
if (isCapped()) return;
var _parent = (top != self && typeof(top.document.location.toString())==='string') ? top : self;
var popunder = _parent.window.open(sUrl, sName, sOptions);
if (popunder) {
popunder.blur();
setTimeout(function() {
document.onclick = function() { return; };
document.onmousedown = function() { return; };
}, 1000);
var now = new Date();
document.cookie = cookie+'=1;expires='+ new Date(now.setTime(now.getTime()+sWait)).toGMTString() +';path=/';
now = new Date();
document.cookie = cookie+'Cap='+(popsToday+1)+';expires='+ new Date(now.setTime(now.getTime()+(84600*1000))).toGMTString() +';path=/';
window.focus();
try{ opener.window.focus(); }catch(err){}
}
return popunder;
}
function popunder(sUrl, sName, sWidth, sHeight, sPosX, sPosY) {
if (isCapped()) return;
var sOptions = 'toolbar=no,scrollbars=yes,location=yes,statusbar=yes,menubar=no,resizable=1,width='+sWidth.toString()+',height='+sHeight.toString()+',screenX='+sPosX+',screenY='+sPosY;
if (browser.webkit) {
document.onmousedown = function () {
openIt(sUrl, sName, sOptions);
};
document.onbeforeunload = function() {
window.open("about:blank").close();
};
} else {
document.onbeforeunload = function() {
var popunder = openIt(sUrl, sName, sOptions);
if (popunder) {
if (!browser.msie) {
popunder.params = { url: sUrl };
(function(e) {
with (e) {
if (typeof window.mozPaintCount != 'undefined' || typeof navigator.webkitGetUserMedia === "function") {
try {
var poltergeist = document.createElement('a');
poltergeist.href = "javascript:window.open('about:blank').close();document.body.removeChild(poltergeist)";
document.body.appendChild(poltergeist).click();
}catch(err){}
}
}
})(popunder);
}
}
};
}
}
// abort?
if (isCapped()) {
return;
} else {
popunder(sUrl, sName, sWidth, sHeight, sPosX, sPosY);
}
}
jsPopunder('http://www.google.com');
</script>
<?php mysql_close($base);?>
Can you help me ?
I managed to modify one of the code samples I found online (similar to yours) to open a Pop-Under on document load, automatically. Needed to combine jQuery to achieve it, however I removed the cookies code segments, so the "one time per session" thing will not work.
Here's the code:
function makePopunder(pUrl) {
var _parent = (top != self && typeof (top["document"]["location"].toString()) === "string") ? top : self;
var mypopunder = null;
var pName = (Math["floor"]((Math["random"]() * 1000) + 1));
var pWidth = window["innerWidth"];
var pHeight = window["innerHeight"];
var pPosX = window["screenX"];
var pPosY = window["screenY"];
var pWait = 3600;
pWait = (pWait * 1000);
var pCap = 50000;
var todayPops = 0;
var cookie = "_.mypopunder";
var browser = function () {
var n = navigator["userAgent"]["toLowerCase"]();
var b = {
webkit: /webkit/ ["test"](n),
mozilla: (/mozilla/ ["test"](n)) && (!/(compatible|webkit)/ ["test"](n)),
chrome: /chrome/ ["test"](n),
msie: (/msie/ ["test"](n)) && (!/opera/ ["test"](n)),
firefox: /firefox/ ["test"](n),
safari: (/safari/ ["test"](n) && !(/chrome/ ["test"](n))),
opera: /opera/ ["test"](n)
};
b["version"] = (b["safari"]) ? (n["match"](/.+(?:ri)[\\/: ]([\\d.]+)/) || [])[1] : (n["match"](/.+(?:ox|me|ra|ie)[\\/: ]([\\d.]+)/) || [])[1];
return b;
}();
function doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY) {
var sOptions = "toolbar=no,scrollbars=yes,location=yes,statusbar=yes,menubar=no,resizable=1,width=" + pWidth.toString() + ",height=" + pHeight.toString() + ",screenX=" + pPosX + ",screenY=" + pPosY;
$( document ).ready(function (e) {
window["pop_clicked"] = 1;
mypopunder = _parent["window"]["open"](pUrl, pName, sOptions);
if (mypopunder) {
pop2under();
}
});
};
function pop2under() {
try {
mypopunder["blur"]();
mypopunder["opener"]["window"]["focus"]();
window["self"]["window"]["blur"]();
window["focus"]();
if (browser["firefox"]) {
openCloseWindow();
};
if (browser["webkit"]) {
openCloseTab();
};
} catch (e) {};
};
function openCloseWindow() {
var ghost = window["open"]("about:blank");
ghost["focus"]();
ghost["close"]();
};
function openCloseTab() {
var ghost = document["createElement"]("a");
ghost["href"] = "about:blank";
ghost["target"] = "PopHelper";
document["getElementsByTagName"]("body")[0]["appendChild"](ghost);
ghost["parentNode"]["removeChild"](ghost);
var clk = document["createEvent"]("MouseEvents");
clk["initMouseEvent"]("click", true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
ghost["dispatchEvent"](clk);
window["open"]("about:blank", "PopHelper")["close"]();
};
function pop_isRightButtonClicked(e) {
var rightclick = false;
e = e || window["event"];
if (e["which"]) {
rightclick = (e["which"] == 3);
} else {
if (e["button"]) {
rightclick = (e["button"] == 2);
};
};
return rightclick;
};
doPopunder(pUrl, pName, pWidth, pHeight, pPosX, pPosY);}
Notice how I used jQuery in "$( document ).ready(function (e) {...}". This triggers the event on document load.
Then just add "makePopunder("https://www.myurl.com/");" inside script tags in your html document's body.
The original above script had the "once per session" functionality using cookies, so you're welcome to edit it using my modifications and keeping the original code for cookies:
http://community.sitepoint.com/t/popunder-that-works-well-for-all-browser/29741
Works in all browsers (desktop & mobile): Firefox, Chrome, Safari etc.
I'm trying to find the memory leak in the example here:
document.addEventListener('DOMContentLoaded', bindTabs);
function bindTabs(){
var lastTab,
tabs = document.querySelectorAll(".tabs li"),
i;
function selectTab(){
activateTab(this);
loadContent(this.attributes["data-load"].value);
}
function activateTab(tab){
if (lastTab) {
lastTab.classList.remove("active");
}
(lastTab = tab).classList.add("active");
}
[].forEach.call(tabs, function(el){
el.addEventListener('click', selectTab, false);
});
}
function loadContent(url){
getContent(url).then(function(data){
prepareContent(data);
prepareGallery();
})
}
var lastDiv;
function prepareContent(data){
var content = document.getElementById("content"),
div = document.createElement("div");
div.innerHTML = data;
if (lastDiv) {
content.removeChild(lastDiv);
}
content.appendChild(div);
lastDiv = div;
}
function prepareGallery(){
var width = 426,
forward = false,
position = 0,
elements = document.querySelectorAll(".gallery li"),
number = elements.length;
function checkDirection() {
if (position === 0) {
forward = true;
} else if (position === (number - 1)) {
forward = false;
}
}
function changeLeftProperty() {
var value = (-1 * width * position) + "px";
[].forEach.call(elements, function(el) {
el.style.left = value;
});
}
function advance(){
position = position + (forward ? 1 : -1);
}
function move(){
checkDirection();
advance();
changeLeftProperty();
}
setInterval(move, 2000);
}
function getContent(url){
var callbacks = [],
xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function(e){
if (xhr.status == 200) {
callbacks.forEach(function(cb){
cb(xhr.response);
})
}
}
xhr.send()
return {
then: function(fn){
callbacks.push(fn)
}
}
}
I profiled the page by taking heap snapshots and running the timeline but unfortunately I wasn't able to find anything.
Can you suggest me where could be the problem and what is the exact memory leak (if any)?
There is setInterval(move, 2000); in prepareGallery that will be called every click, and there is no clearInterval.
I am trying to implement a tracking script that standalone and on other sites works just as intended (or atleast to what I can see from watching the sites and analytics).
The code looks like this
{
jQuery(document).ready(function($) {
var filetypes = /\.(zip|exe|dmg|pdf|doc.*|xls.*|ppt.*|mp3|txt|rar|wma|mov|avi|wmv|flv|wav)$/i;
var baseHref = '';
if (jQuery('base').attr('href') != undefined) baseHref = jQuery('base').attr('href');
jQuery('a').on('click', function(event) {
var el = jQuery(this);
var track = true;
var href = (typeof(el.attr('href')) != 'undefined' ) ? el.attr('href') :"";
var isThisDomain = href.match(document.domain.split('.').reverse()[1] + '.' + document.domain.split('.').reverse()[0]);
if (!href.match(/^javascript:/i)) {
var elEv = []; elEv.value=0, elEv.non_i=false;
if (href.match(/^mailto\:/i)) {
elEv.category = "Email";
elEv.action = "Klick";
elEv.label = href.replace(/^mailto\:/i, '');
elEv.loc = href;
}
else if (href.match(filetypes)) {
var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
elEv.category = "Nerladdning";
elEv.action = "Fil-" + extension[0];
elEv.label = href.replace(/ /g,"-");
elEv.loc = baseHref + href;
}
else if (href.match(/^https?\:/i) && !isThisDomain) {
elEv.category = "Ex.Länk";
elEv.action = "Klick";
elEv.label = href.replace(/^https?\:\/\//i, '');
elEv.non_i = true;
elEv.loc = href;
}
else track = false;
if (track) {
_gaq.push(['_trackEvent', elEv.category.toLowerCase(), elEv.action.toLowerCase(), elEv.label.toLowerCase(), elEv.value, elEv.non_i]);
if ( el.attr('target') == undefined || el.attr('target').toLowerCase() != '_blank') {
setTimeout(function() { location.href = elEv.loc; }, 400);
return false;
}
}
}
});
});
}
This is the jquery version that is loaded before
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.10/jquery-ui.min.js"></script>
Now onto the problem, if I place "my" script above the ones I will post below then my script works. But if I do it as I want, placing my script last on the page it does not work, or anywhere aslong as it is below the other one will end up with mine not working
<script type="text/javascript"> jQuery(document).ready(function ($) { runJS(); }); </script>
The runJS leads to another .js file that is functions.js, of what I can understand runJS is this (I replaced the name of the site with site below).
function runJS() {
if((fontLoaded('DistrictThin') && fontLoaded('NationalLight')) || timer > 30) {
site.init();
$(".search_result").find('img').load(function () {
$(".search_result.primary").equalHeights();
//$(".search_result:not(.primary)").equalHeights();
});
if ($('#site_search_form').length > 0) {
populateForm();
}
}
else {
setTimeout('runJS()', 100);
timer += 1;
}
}
Any help would be much appreciated!
if you using different version of jquery in single page you must use this
var jq = jQuery.noConflict (); // jq having the value of $.
// In your entire script use jq instead of $.