modal images generate wrong code under FF and IE - javascript

My modal images seems to be working only under Chrome. In Firefox and Internet Expoler modal images generate code with errors:
<img src="" http:="" localhost="" ceramikakornak="" images="" realizacje="" klasyczne="" 3.jpg""="" class="img-responsive">
In Chrome modal windows is ok and looks:
<img src="images/realizacje/1.jpg" class="img-responsive">
JavaScript which i use to generate Modal Window:
$(document).ready(function() {
$('.realizacje-fota').each(function(){
var checkClass = $(this);
var image_url = checkClass.css('background-image'),
image;
// Remove url() or in case of Chrome url("")
image_url = image_url.match(/^url\("?(.+?)"?\)$/);
if (image_url[1]) {
image_url = image_url[1];
image = new Image();
// just in case it is not already loaded
$(image).load(function () {
// alert(image.width + 'x' + image.height);
var ratio = image.width/image.height;
if (ratio > 1) {
checkClass.addClass("realizacje-fota-pion");
}
else if (ratio <= 1) {
checkClass.addClass("realizacje-fota-poziom");
}
});
image.src = image_url;
}
});
});
$(document).ready(function(){
$('.lazy div').on('click',function(){
var src = $(this).css('background-image');
var src = src.substring(4, src.length);
var src = src.substring(0, src.length - 1);
var img = '<img src="' + src + '" class="img-responsive"/>';
var index = $(this).parent('div').index();
var html = '';
html += img;
html += '<div style="clear:both;display:block;">';
html += '<a class="controls next" href="'+ (index+1) + '">next »</a>';
html += '<a class="controls previous" href="' + (index) + '">« prev</a>'
html += '</div>';
$('#myModal').modal();
$('#myModal').on('shown.bs.modal', function(){
$('#myModal .modal-body').html(html);
//new code
$('a.controls').trigger('click');
})
$('#myModal').on('hidden.bs.modal', function(){
$('#myModal .modal-body').html('');
});
});
})
$(document).on('click', 'a.controls', function(){
var index = $(this).attr('href');
var src = $('.row div:nth-child('+ index +') img').attr('src');
$('.modal-body div').str('scr', src);
var newPrevIndex = parseInt(index) - 1;
var newNextIndex = parseInt(newPrevIndex) + 2;
if($(this).hasClass('previous')){
$(this).attr('href', newPrevIndex);
$('a.next').attr('href', newNextIndex);
}else{
$(this).attr('href', newNextIndex);
$('a.previous').attr('href', newPrevIndex);
}
var total = $('.row div').length + 1;
//hide next button
if(total === newNextIndex){
$('a.next').hide();
}else{
$('a.next').show()
}
//hide previous button
if(newPrevIndex === 0){
$('a.previous').hide();
}else{
$('a.previous').show()
}
return false;
});

Related

JavaScript Input File Not Storing Contents When I Add More Content to Upload

Alright so I'm looking so much to this code that I can't figure it out anymore.
So I have a "Select Files" button that I allow users choose multiple files to upload:
<input type="file" multiple id="gallery-photo-add" name="file[]" class="form-control custom-file-input btn btn-info" value="">
Below is the JavaScript. Everything works except this behavior:
I click and select 1 file to send. It does everything right and send it to the preview. If I click to add more files, it resets the input value and remove the ones I added before. Just from the input, not from the previews.
var imagesPreview = function (input) {
if (input.files) {
// remove main principal
$('.no-image').parent().remove();
// get total files sent this time
var filesAmount = input.files.length;
// get existent files in carousel
var totalItens = $('.carousel-inner > .item').length;
// sum all items
var itensSum = (filesAmount + totalItens);
// update total in title
$('.slider-total-items > span').html('(' + itensSum + ')');
var reader = new FileReader();
for (i = 0; i < filesAmount; i++) {
reader.onload = function (event) {
$('.carousel-inner > .item').removeClass('active');
if (input.files[0].type.substr(0, 5) == 'video') {
var html = '<div class="item ' + (i == 0 ? 'active' : '') + '"><video width="320" height="210" controls><source src="' + event.target.result + '"></video></div>';
return
}
if (filesAmount > 1) {
var html = '<div class="item text-center posts-images-edit ' + (i == filesAmount ? 'active' : '') + '"><img src="' + event.target.result + '"></div>';
} else {
var html = '<div class="item text-center posts-images-edit ' + (i == 1 ? 'active' : '') + '"><img src="' + event.target.result + '"></div>';
}
$(html).appendTo('.carousel-inner');
}
if (itensSum > 1) {
$('#galleryControls').removeClass('hide');
}
reader.readAsDataURL(input.files[i]);
}
}
};
$(function () {
$('#gallery-photo-add').on('change', function () {
imagesPreview(this);
});
});
How can I keep all the files selected on the input?
Thanks
This is just how file inputs work. Every change represents a new FileList.
If you want to incrementally build your own list, you'll need to maintain it outside the <input> element
const allFilesSelectedEver = [];
const imagesPreview = (input) => {
allFilesSelectedEver.push(...input.files);
// now use `allFilesSelectedEver` instead of `input.files`
// ...
};

Insert iframe and remove it by js

This code append a vimeo video. But when the vimeo video appears, I cant close it pressing buttonClose. When I press buttonClose It should delte the container vimeoPop. What's the issue?
<div class="vimeo-video">
<div class="video">
<a class="" href="#" yt-id="535941">
<img>
</a>
</div>
</div>
var i = 1;
var str1 = "n";
$(".vimeo-video").each(function (index, value) {
var maindiv = str1 + i;
$(this).addClass(maindiv);
$(".vimeo-video." + maindiv + " a").click(function (e) {
e.preventDefault();
var src = $(this).attr("yt-id");
var link = "https://player.vimeo.com/video/" + src + "?autoplay=1";
var iframe =
'<div class="vimeoPop"><div class="buttonClose"><span></span><span></span></div><iframe frameborder="0" src="' +
link +
'" allowfullscreen></iframe></div>';
$(".vimeo-video." + maindiv + " .video").append(iframe);
});
$(document).on('click', '.buttonClose', function () {
$(".vimeo-video" + maindiv + " .vimeoPop").remove();
});
i++;
});
you are missing selector . for the class at remove line
instead of selecting ".vimeo-video.n1" you are selecting ".vimeo-videon1"
var i = 1;
var str1 = "n";
$(".vimeo-video").each(function (index, value) {
var maindiv = str1 + i;
$(this).addClass(maindiv);
$(".vimeo-video." + maindiv + " a").click(function (e) {
e.preventDefault();
var src = $(this).attr("yt-id");
var link = "https://player.vimeo.com/video/" + src + "?autoplay=1";
var iframe =
'<div class="vimeoPop"><div class="buttonClose"><span>Close</span><span></span></div><iframe frameborder="0" src="' +
link +
'" allowfullscreen></iframe></div>';
$(".vimeo-video." + maindiv + " .video").append(iframe);
});
$(document).on('click', '.buttonClose', function () {
$(".vimeo-video." + maindiv + " .vimeoPop").remove();
});
i++;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="vimeo-video">
<div class="video">
<a class="" href="#" yt-id="535941">
<img>Click me
</a>
</div>
</div>

Checking if image exists before executing code

I have an array of image links that I'm getting from reddit, but some image urls are broken. I want to skip over broken image links.
This thread suggested using .width to see if an image exists. I tried using this answer to wait for image links to load before executing code but it's not working, it's skipping right over my if(this.width>0) check.
var imgLinksArray = Array.from(imgLinks);
document.getElementById('photoGrid').innerHTML = "";
for (i = 0; i < imgLinks.length; i++) {
var workingImgLink = imgLinksArray[i]
var img = new Image();
img.onload = function() {
console.log(this);
console.log(this.src + " Width: " + this.width);
for (i = 0; i < imgLinks.length; i++) {
var workingImgLink = imgLinksArray[i]
if (this.width > 0) {
console.log(this.width);
if (workingImgLink.search("webm") >= 0) {
document.getElementById('photoGrid').innerHTML += '<video autoplay loop class="box-wrapper"> <source type="video/webm" src= "' + workingImgLink + '" data-url= "' + workingImgLink + '" class="box" style=background-image:url("' + workingImgLink + '")></video>';
} else {
document.getElementById('photoGrid').innerHTML += '<div class="box-wrapper"> <div data-url= "' + workingImgLink + '" class="box" style=background-image:url("' + workingImgLink + '")></div></div>';
}
}
}
}
img.src = workingImgLink;
var bgImgWidth = img.width;
var bgImgHeight = img.height;
}
I only want to execute the innerHTML code if I know the image exists. Any suggestions about how to go about this?

Console returns that a var isn't defined, but it is

I've got this code which basically.. On click of a div, it loads up the paragraph and inserts it into the twitch api url. The script should be working but what happens is after the fadeOut the div remains empty. The console returns the error that twitchData isn't defined, but it is.
So it should work like this: Click on the div -> Understand which div was clicked -< fadeOut + empty() the div -> get the paragraph text -> replace it inside the twitchApi link etcetera.
$('.games > div').click((e) => {
var gameDiv = $(this); // Get which div was clicked here
$('#twitch').children().fadeOut(500).promise().then(function() {
$('#twitch').empty();
$(function() {
var i = 0;
var gameName = $(e.target).text().replace(' ', '%20'); // Get the game name
console.log(gameName);
var twitchApi = "https://api.twitch.tv/kraken/streams?game=" +gameName; // Build the URL here
var twitchData;
$.getJSON(twitchApi, function(json) {
twitchData = json.streams;
setData()
});
});
function setData() {
var j = twitchData.length > (i + 9) ? (i + 9) : twitchData.length; for (; i < j; i++) {
var streamGame = twitchData[i].game;
var streamThumb = twitchData[i].preview.medium;
var streamVideo = twitchData[i].channel.name;
var img = $('<img style="width: 250px; height: 250px;" src="' + streamThumb + '"/>');
$('#twitch').append(img);
img.click(function() {
$('#twitch iframe').remove()
$('#twitch').append( '<iframe style="width: 600px;" src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
});
}
}
$('#load').click(function() {
setData();
});
});
});
This is a scope issue. You need to pass 'twitchData' into your setData function. Right now it is only defined within your click event.
$('.games > div').click((e) => {
var gameDiv = $(this); // Get which div was clicked here
$('#twitch').children().fadeOut(500).promise().then(function() {
$('#twitch').empty();
$(function() {
var i = 0;
var gameName = $(e.target).text().replace(' ', '%20'); // Get the game name
console.log(gameName);
var twitchApi = "https://api.twitch.tv/kraken/streams?game=" +gameName; // Build the URL here
$.getJSON(twitchApi, function(json) {
setData(json.streams)
});
});
function setData(twitchData) {
var j = twitchData.length > (i + 9) ? (i + 9) : twitchData.length; for (; i < j; i++) {
var streamGame = twitchData[i].game;
var streamThumb = twitchData[i].preview.medium;
var streamVideo = twitchData[i].channel.name;
var img = $('<img style="width: 250px; height: 250px;" src="' + streamThumb + '"/>');
$('#twitch').append(img);
img.click(function() {
$('#twitch iframe').remove()
$('#twitch').append( '<iframe style="width: 600px;" src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
});
}
}
});
});

Add description to lightbox image

I'm using this lightbox plugin: http://s.codepen.io/schadeck/pen/gjbqr
I would like to know if there is any way to add a simple description attribute in my current code.
What I want to achieve is a description text on the bottom of the image in the lightbox. I've looked for a solution, but nothing seems to apply for the lightbox.js script I'm using.
Here is the code:
jQuery(document).ready(function($) {
// global variables for script
var current, size;
$('.lightboxTrigger').click(function(e) {
// prevent default click event
e.preventDefault();
// grab href from clicked element
var image_href = $(this).attr("href");
// determine the index of clicked trigger
var slideNum = $('.lightboxTrigger').index(this);
// find out if #lightbox exists
if ($('#lightbox').length > 0) {
// #lightbox exists
$('#lightbox').fadeIn(300);
// #lightbox does not exist - create and insert (runs 1st time only)
} else {
// create HTML markup for lightbox window
var lightbox =
'<div id="lightbox">' +
'<p>Clique para fechar</p>' +
'<div id="slideshow">' +
'<ul></ul>' +
'<div class="nav">' +
'Anterior' +
'Proxima' +
'</div>' +
'</div>' +
'</div>';
//insert lightbox HTML into page
$('body').append(lightbox);
// fill lightbox with .lightboxTrigger hrefs in #imageSet
$('#imageSet').find('.lightboxTrigger').each(function() {
var $href = $(this).attr('href');
$('#slideshow ul').append(
'<li>' +
'<img src="' + $href + '">' +
'</li>'
);
});
}
// setting size based on number of objects in slideshow
size = $('#slideshow ul > li').length;
// hide all slide, then show the selected slide
$('#slideshow ul > li').hide();
$('#slideshow ul > li:eq(' + slideNum + ')').show();
// set current to selected slide
current = slideNum;
});
//Click anywhere on the page to get rid of lightbox window
$('body').on('click', '#lightbox', function() { // using .on() instead of .live(). more modern, and fixes event bubbling issues
$('#lightbox').fadeOut(300);
});
// show/hide navigation when hovering over #slideshow
$('body').on(
{ mouseenter: function() {
$('.nav').fadeIn(300);
}, mouseleave: function() {
$('.nav').fadeOut(300);
}
},'#slideshow');
// navigation prev/next
$('body').on('click', '.slide-nav', function(e) {
// prevent default click event, and prevent event bubbling to prevent lightbox from closing
e.preventDefault();
e.stopPropagation();
var $this = $(this);
var dest;
// looking for .prev
if ($this.hasClass('prev')) {
dest = current - 1;
if (dest < 0) {
dest = size - 1;
}
} else {
// in absence of .prev, assume .next
dest = current + 1;
if (dest > size - 1) {
dest = 0;
}
}
// fadeOut curent slide, FadeIn next/prev slide
$('#slideshow ul > li:eq(' + current + ')').fadeOut(750);
$('#slideshow ul > li:eq(' + dest + ')').fadeIn(750);
// update current slide
current = dest;
});
});
HTML:
<ul id="imageSet">
<li><img src="" title=""></li>
</ul>
I haven't looked at the script but you could try this:
var desc = ['some description title', 'another description title', 'etc'];
$('body').append(lightbox);
// fill lightbox with .lightboxTrigger hrefs in #imageSet
$('#imageSet').find('.lightboxTrigger').each(function(index) {
var $href = $(this).attr('href');
$('#slideshow ul').append(
'<li>' +
'<img src="' + $href + '">' +
'<span>' + desc[index] + '</span>' +
'</li>'
);
});

Categories

Resources