Lazy Loading a Repeating Iframe Div - javascript

I have a lazy-load code block here:
(function($){
var items = [];
function winPos(win) {
return { x: 0, y: 0, x2: win.width() - 1, y2: win.height() - 1 };
}
function pos(win, el) {
var p = el.offset();
var x = p.left - win.scrollLeft();
var y = p.top - win.scrollTop();
return { x: x, y: y, x2: x + el.width() -1, y2: y + el.height() - 1 };
}
function intersects(a, b) {
return !(a.x2 < b.x || a.x > b.x2 || a.y2 < b.y || a.y > b.y2);
}
function check(win, w, item) {
var p = pos(win, $(item.el));
var s = intersects(w, p);
if (s != item.shown) {
item.shown = s;
(s ? item.show : item.hide).call(item.el);
}
}
$.fn.visible = function(show, hide){
var win = $(window), w = winPos(win);
return this.each(function(i, el){
var item = { el: el, show: show, hide: hide, shown: false };
items.push(item);
check(win, w, item);
});
};
$(window).on('scroll resize', function(e){
var win = $(window), w = winPos(win);
for (var i = 0; i < items.length; i++) {
check(win, w, items[i]);
}
});
})(jQuery);
// Lazy loading images plugin
(function($){
$.fn.lazyImage = function(){
return this.visible(function(){
$(this).append($('<img>', {'src': $(this).data('src') }).css('opacity', 0).load(function(){
$(this).animate({ opacity: 1 });
}));
}, function(){
$(this).empty();
});
};
})(jQuery);
// Usage
$('div').lazyImage();
https://jsfiddle.net/Guffa/u7bcms27/
I want to lazy load each iframe div.
*
Here's my code, that gets links and titles from the Reddit API, and loads the videos into Iframes.
fetch('https://www.reddit.com/r/cleanupearth.json')
.then(res=>res.json())
.then(res=>res.data.children)
.then(res=>res.map(post=>({
// author: post.data.author,
link: post.data.url,
img: post.data.thumbnail,
title: post.data.title
})))
.then(res=>res.map(render))
.then(res=>console.log(res))
const app = document.querySelector('#app');
const render = post => {
const node = document.createElement('div');
node.innerHTML= `${post.title}`;
node.className= 'clip-title';
app.appendChild(node);
//node.style.fontSize = "50px";
var regExp = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var url = post.link;
// var url = "https://www.youtube.com/watch?v=MPmKEi4xXMg";
var match = url.match(regExp);
var strippedURL = match[2];
//alert("strippedURL is " + strippedURL);
if (match && match[2].length == 11) {
console.log(match[2]);
} else {
//error
console.log('error');
}
var a = document.createElement('iframe');
// iframe.id = 'appiframe';
a.className = "clip-content"
a.src = "https://www.youtube.com/embed/" + strippedURL; //add your iframe path here
a.width = "100%";
a.height = "100%";
a.padding = "500px";
app.style.textAlign = "center";
document.querySelector('#app').appendChild(a);
}
*
Here's an fiddle of the two snippets together.
https://jsfiddle.net/p5tL6jvr/
The original snippet creates an empty array called items:
var items = [];
and loads images into an append function;
$(this).append($('<img>', {'src': $(this).data('src') }).css('opacity', 0).load(function()
I could load the entire id=#app div into the items array, and swap the img line for a line that creates iframes. What is the best way to approach this?
BTW, if anyone knows of a succinct way to do this in pure Javascript, instead of JQuery, that would be interesting to read.

Related

pageLoaded function not fired

I am creating todo app using nativescript javascript platform. please find the js code below. list items not showing in the landing page. while i tried to debug exports.pageloaded function not triggered. please point me what wents wrongs with the code. let me know if anything needed.
Thanks in advance!.
var Observable = require("tns-core-modules/data/observable");
var ObservableArray = require("tns-core-modules/data/observable-array");
var pageArray = new ObservableArray.ObservableArray();
var pageData = new Observable.Observable({
notes: pageArray
});
var view = require("tns-core-modules/ui/core/view");
var uiEnums = require("tns-core-modules/ui/enums");
var animation = require("tns-core-modules/ui/animation");
var appSettings = require("application-settings");
var fs = require("file-system");
var page;
var notesArr = [];
var current_index = -1;
exports.pageLoaded = function(args) {
page = args.object;
pageData.set('showForm', true);
var new_note_title = appSettings.getString('new_note_title');
var notes = appSettings.getString('notes');
if(!notes){
notes = [
{
index: 0,
title: '100 push ups'
},
{
index: 1,
title: '100 sit ups'
},
{
index: 2,
title: '100 squats'
},
{
index: 3,
title: '10km running'
}
];
}else{
notes = JSON.parse(notes);
}
notesArr = notes;
if(!pageArray.length){
for(var x = 0; x < notes.length; x++){
current_index += 1;
pageArray.push(notes[x]);
}
}
pageData.set('item_title', new_note_title);
args.object.bindingContext = pageData;
view.getViewById(page, 'form').animate({
translate: { x: 0, y: 160 },
duration: 800,
});
}
exports.newNote = function() {
var showForm = pageData.get('showForm');
var top_position = (showForm) ? -160 : 160;
var list_visibility = (showForm) ? 1 : 0;
view.getViewById(page, 'list').animate({
opacity: list_visibility,
duration: 400
});
view.getViewById(page, 'form').animate({
translate: { x: 0, y: top_position },
duration: 800,
});
pageData.set('showForm', !showForm);
}
exports.btnLoaded = function (args) {
var btn = args.object;
btn.android.setFocusable(false);
}
exports.saveNote = function() {
var new_note_title = pageData.get('item_title');
var new_note_photo = pageData.get('attachment_img');
current_index += 1;
var new_index = current_index;
var new_item = {
index: new_index,
title: new_note_title,
photo: new_note_photo,
show_photo: false
};
notesArr.push(new_item);
pageArray.push(new_item);
appSettings.setString('notes', JSON.stringify(notesArr));
appSettings.setNumber('current_index', new_index);
appSettings.remove('new_note_title');
appSettings.remove('new_note_photo');
pageData.set('showForm', false);
pageData.set('item_title', '');
pageData.set('attachment_img', null);
view.getViewById(page, 'list').animate({
opacity: 1,
duration: 400
});
view.getViewById(page, 'form').animate({
translate: { x: 0, y: -160 },
duration: 800,
});
}
exports.deleteNote = function(args){
var target = args.object;
var index_to_delete = notesArr.map(function(e) {
return e.index;
}).indexOf(target.index);
notesArr.map(function(item, index){
if(index == index_to_delete){
notesArr.splice(index_to_delete, 1);
pageArray.splice(index_to_delete, 1);
return false;
}
});
appSettings.setString('notes', JSON.stringify(notesArr));
}
Please find the playground here
function pageLoaded(args) {
alert('pageloaded');
...
}
and in the end
exports.pageLoaded = pageLoaded;
It is poping up the alert on load and pageLoaded function is getting fired.

Improving Existing Horizontal "Roulette" Scroller

I created a prototype for a horizontal scroller which will select a winner in an animated fashion. I am looking to improve this by programmatically highlighting the selected image under the indicator. I have figured out how to get it to scroll where I want, but I cannot figure out how to programmatically select the image after it's won.
Currently using:
HTML
CSS
jQuery
GSAP TimeLineMax
Working Example: http://codepen.io/ByteKnight13/pen/950a1a0d277fc0204d1827120bdcc090/
Current Code:
if (!String.prototype.format) {
String.prototype.format = function () {
var args = arguments;
return this.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match;
});
};
}
$(window).load(function () {
console.log('Window loaded!');
var $roulette = $('#roulette-images-list');
$roulette.html(generateRouletteImages(200));
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getPositionOfWinner(winner) {
var widthOfImg = $('#roulette-img0').width();
var minDistanceToEdgeAllowed = 4;
var desiredImg = $('#roulette-img' + winner.toString());
var minPos = desiredImg.position().left + minDistanceToEdgeAllowed;
var maxPos = desiredImg.position().left + widthOfImg - minDistanceToEdgeAllowed;
console.log('Position.Left: {0} | Offset().left: {1}'.format(desiredImg.position().left, desiredImg.offset().left));
return getRandomInt(minPos, maxPos);
}
function printLeftOfRouletteSpinner() {
var pos = $('#roulette-images-list').position().left;
if (pos % 100 == 0) console.log(pos);
}
function rouletteSpin(destImg) {
if (!destImg) destImg = 40;
var tl = new TimelineMax({onUpdate: printLeftOfRouletteSpinner}),
rouletteImages = $('#roulette-images-list'),
startLeft = rouletteImages.position().left;
tl//.to(rouletteImages, 0, {x: 5000})
.to(rouletteImages, 10, {x: getPositionOfWinner(destImg) * -1, ease:Power4.easeOut})
.to(rouletteImages, 0, {x: 0}, 11);
}
$('#spin').click(function () {
var winner = $('#winner-text').val();
//if (isNaN(winner) || winner > 49) alert('Enter 0 through 49');
rouletteSpin(winner);
});
function getRandomColor() {
return ((1 << 24) * Math.random() | 0).toString(16)
}
function generateRouletteImages(howMany) {
var imgTemplate = '<img src="{0}" class="{1}" id="roulette-img{2}">';
var imgClass = 'roulette-img';
var imgSrcTemplate = 'http://placehold.it/{0}/{1}?text={2}';
var completedRouletteImages = [];
for (var i = 0; i < howMany; i++) {
var color = getRandomColor();
var imgSrc = imgSrcTemplate.format('80', color, i);
var completedTemplate = imgTemplate.format(imgSrc, imgClass, i);
completedRouletteImages.push('<li>' + completedTemplate + '</li>');
}
return completedRouletteImages;
}
});
There is an onComplete parameter on TimelineMax. Combining that with the onCompleteParams parameter, you can pass the winner image reference to the onComplete callback.
new TimelineMax({
onComplete: timelineFinished,
onCompleteParams: [ destImg ]
})
function timelineFinished(destImg){
// this is where you highlight your winner
$('#roulette-img' + destImg).css({
border: '3px solid red'
});
}
Also, the roulette was resetting after to completed the spin, so I removed the last: .to(rouletteImages, 0, {x: 0}, 11)
Its a pretty rough selection, but you can clean it up with some CSS or whatever you are trying to achieve.
Working Example:
http://codepen.io/kingkode/pen/EyKwJW

How to get a variable into a function from another under "use strict"

I really don't know how to get the following variable from a function into another function. I've read most of the articles and answers about that, and I think my example is more complex. Otherwise, I'm doing it wrong.
This is the function I'm using to determine the value of the wpbar variable. I even could start with $(document).ready(function(), but I removed it for the example:
function wp_adminbar() {
"use strict";
var win = $(window),
wpbar = 0;
if ($('body').hasClass('admin-bar')) {
win.on("resize load",function(){
var wpbar, w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth;
if (x <= 782) {
wpbar = 46;
} else if (x > 782) {
wpbar = 32;
}
});
}
return wpbar;
}
I want to use the variable wpbar into this another function:
$(document).ready(function($) {
"use strict";
var wpbar = wp_adminbar();
console.log(wpbar); // Returns: 0
});
I'm stuck in that. Edit: Actually, return wpbar; is not working at all.
Edit: Full code of a function contaning the first function. In this case, it works:
$(document).ready(function($) {
"use strict";
var win = $(window),
nav_fixed = $('.enable-fixed'),
header = $('#header-v1');
if (!nav_fixed.length || !header.length) return;
// WordPress Toolbar
var wpbar = 0;
if ($('body').hasClass('admin-bar')) {
win.on("resize load",function(){
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth;
if (x <= 782) {
wpbar = 46;
} else if (x > 782) {
wpbar = 32;
}
});
}
var max_h = 89,
min_h = 55,
var_h = max_h - min_h,
menu = $('.sticky-wrapper-v1, #header-v1, #header-v1 .wrap, #header-v1 .menuwrap ul:first-child > li > a, #header-v1 .main-nav-search a'),
logo = $('#header-v1 #logo, #header-v1 #logo img'),
nav = $('#navigation'),
set_height = function(){
var st = win.scrollTop() + wpbar,
new_h = 0,
new_p = 0,
wrapper = $('.sticky-wrapper-v1'),
top_p = wrapper.offset().top;
if (st <= top_p) {
new_h = max_h;
new_p = 0;
} else if (st <= (top_p + var_h)) {
new_h = max_h - st + top_p;
new_p = st - top_p;
header.removeClass("header-scrolled");
} else {
new_h = min_h;
new_p = var_h;
header.addClass("header-scrolled");
}
wrapper.css('margin-bottom', new_p);
menu.css({'height': new_h + 'px', 'lineHeight': new_h + 'px'});
logo.css({'maxHeight': new_h + 'px'});
nav.css({'height': new_h + 'px'});
};
win.one("resize",function(){
$(".navbtn").toggle(function() {
set_height;
}, function () {
set_height;
});
set_height;
});
win.on('debouncedresize', function(){
max_h = $(menu).attr('style',"").filter(':first').height();
set_height();
});
win.on('scroll', function(){
window.requestAnimationFrame( set_height );
});
set_height();
});

Drag and lock inside of the parent

Online sample http://jsfiddle.net/dhCLd/
A simple drag magnify,
(function($) {
$.fn.drag = function(opt) {
opt = $.extend({
handle: "",
cursor:"move"}, opt);
if(opt.handle === "") {
var $el = this;
} else {
var $el = this.find(opt.handle);
}
return $el.css('cursor', opt.cursor).on("mousedown", function(e) {
if(opt.handle === "") {
var $drag = $(this).addClass('draggable');
} else {
var $drag = $(this).addClass('active-handle').parent().addClass('draggable');
}
var z_idx = $drag.css('z-index'),
native_width = 0,
native_height = 0;
$drag.css('z-index', 1000).parents('.magnify').on("mousemove", function(e) {
if(!native_width && !native_height){
var image_object = new Image();
image_object.src = $(".small").attr("src");
native_width = image_object.width;
native_height = image_object.height;
}else{
var magnify_offset = $drag.parents('.magnify').offset();
var mx = e.pageX - magnify_offset.left;
var my = e.pageY - magnify_offset.top;
var rx = Math.round(mx/$(".small").width()*native_width - $drag.width()/2)*-1;
var ry = Math.round(my/$(".small").height()*native_height - $drag.height()/2)*-1;
var px = mx - $(".large").width()/2;
var py = my - $(".large").height()/2;
var bgp = rx + "px " + ry + "px";
$('.draggable').css({left:px, top:py, backgroundPosition: bgp}).on("mouseup", function() {
$(this).removeClass('draggable').css('z-index', z_idx);
});
}
});
e.preventDefault();
}).on("mouseup", function() {
if(opt.handle === "") {
$(this).removeClass('draggable');
} else {
$(this).removeClass('active-handle').parent().removeClass('draggable');
}
});
}
})(jQuery);
How can I make the "magnify" stops at the edges around the .small` image, if outside of the image then undraggable. If someone could help?
You can just limit the values of mx (in range [0,magnify's width]) and my (in range [0, magnify's height]):
var magnify = $drag.closest('.magnify');
var magnify_offset = magnify.offset();
var mx = Math.min(Math.max(e.pageX - magnify_offset.left,0),magnify.width());
var my = Math.min(Math.max(e.pageY - magnify_offset.top,0), magnify.height());
Updated demo.
To make the magnifying glass undraggable when it's outside a bounded area, simply test the position of the background image as it is being drag:
var cH = 175/2; //Half of the magnifying glass
if(rx > cH|| ry > cH || rx < -579 + cH || ry < -1107 + cH){ //579 and 1107 are the dimension of the background image
$(this).trigger("mouseup"); //Make it undraggable
return false;
}

how to completely remove

please help to remove the new Bullet. jsfiddle
after the object it moves across the screen from the bottom up. coordinate with y <= 5px method works helper.deleteElement (), but the object is still there exists (see the console - console.log ('move') ;)
I need to to be removed completely
js:
Bullet = function(bulletId){
var self = this;
self.id = bulletId;
self.x = 100;
self.y = 500;
self.move = function(){
console.log('move');
var offsetY = -10,
newY = self.y + offsetY;
if(newY <= 5){
helper.deleteElement(self.id);
if(observerable.removeListener(this, "makeMoveBullet", "move")){
console.log('dont worked!');
}
}
self.y = newY;
self.render(self.x, newY);
return;
};
self.render = function(x, y){
$('#' +self.id).css({
'left': (self.x = x || self.x) + 'px',
'top': (self.y = y || self.y) + 'px'
}).appendTo('#wrap');
return;
};
self.init = function(playerX, playerY){
$('<div class="bullet" id="' + self.id + '" />').appendTo('#wrap');
self.x = playerX + 31;
self.y = playerY - 9;
self.render(self.x, self.y);
return;
};
};
// ------------------------------------------------------------------------------------ observer
var observerable = {
listeners: {},
addListener: function (object, evt, callback) {       
if (!this.listeners.hasOwnProperty(evt)) {           
this.listeners[evt] = [];    
}        
this.listeners[evt].push(object[callback]);       
},
removeListener: function (object, evt, callback) {       
if (this.listeners.hasOwnProperty(evt)) {      
var i, length;     
        
for (i = 0, length = this.listeners[evt].length; i < length; i += 1) {               
if (this.listeners[evt][i] === object[callback]) {                   
this.listeners[evt].splice(i, 1);        
}      
}    
}  
},
    
publisher: function (evt, args) {       
if (this.listeners.hasOwnProperty(evt)){                       
var i, length;       
                          
for (i = 0, length = this.listeners[evt].length; i < length; i += 1){                
this.listeners[evt][i](args);      
}            
}                            
}
};
// ------------------------------------------------------------------------------------ helper
function Helper(){
this.deleteElement = function(id){
$('#' + id).remove();
return;
};
};
// ------------------------------------------------------------------------------------ init
var helper = new Helper();
bullet = new Bullet('bullet_0');
bullet.init(500, 500);
observerable.addListener(bullet, "makeMoveBullet", "move");
setInterval(function(){
observerable.publisher("makeMoveBullet");
}, 100);
JavaScript uses a Garbage Collector to remove unused variables. I would say to do something like this:
delete this.x; delete this.y ; ... ; delete this;
When you want to remove the object (also remove it from any other external data structures). Remove all it's properties then the object itself. Then the GC should remove it.
setInterval returns an interval identifier. Clear the interval using clearInterval function when you don't want more executions of the interval.
var int = setInterval(...);
...
clearInterval(int);
removeListener: function (object, evt, callback) {
if (this.listeners.hasOwnProperty(evt)) {
var i, length;
for (i = 0, length = this.listeners[evt].length; i < length; i += 1) {
if (this.listeners[evt][i] === object[callback]) {
this.listeners[evt].splice(i, 1);
}
}
}
}
object[callback] is always undefined so this.listeners[evt].splice(i, 1); cannot be executed;

Categories

Resources