Why doesn't the video tag load in this video player web component? - html5-video

I'm trying to build a video player Web Component, but I can't seem to get the video and source elements to render properly.
customElements.define('video-player',
class extends HTMLElement {
constructor() {
super();
const template = document.getElementById('video-player-template').content;
console.log(template)
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(template.cloneNode(true));
}
}
);
<template id="video-player-template">
<video controls width="720" height="380" muted autoplay>
<slot name="video-src" />
</video>
<slot></slot>
</template>
<video-player>
<h1>Video player web component</h1>
<source slot="video-src" src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm" type="video/webm" />
</video-player>
Why doesn't the video element render?

see the documentation: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video
<video> wants a <source> element as immediate child,
thus you can't use a <slot> there.
(the same is true for <table>, which can't have <slot>)
You extract the src from your <video-player src="..."> Web Component,
then create that <source> tag.
I have added all shadowDOM styling options for a complete example
customElements.define('video-player',
class extends HTMLElement {
constructor() {
super()
.attachShadow({mode:'open'})
.append(document.getElementById(this.nodeName).content.cloneNode(true));
}
connectedCallback() {
let src = this.getAttribute("source");
let ext = src.split(".").slice(-1)[0];
this.shadowRoot
.querySelector("video")
.innerHTML = `<source src="${src}" type="video/${ext}">`;
}
}
);
<video-player source="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm">
<span slot="title">A beautiful video</span>
<div class="desc">My video description</div>
</video-player>
<video-player source="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm">
<span slot="title">Another beautiful video</span>
<div class="desc">And more description</div>
</video-player>
<template id="VIDEO-PLAYER">
<style>
:host { display:inline-block }
h1 { margin:0px;background:var(--bgcolor,green);text-align:center }
</style>
<div part="videoContainer">
<h1><slot name="title"></slot></h1>
<video controls width="100%" muted></video>
<div><slot><!-- all non-slot labeled content goes here --></slot></div>
</div>
</template>
<style>
video-player {
font: 10px Arial; /* Inheritable styles style shadowDOM */
width: 240px;
--bgcolor: gold; /* CSS properties can style shadowDOM */
}
.desc { /* container/global CSS styles slotted content!!!! */
width: 100%;
background: beige;
}
::part(videoContainer){ /* shadowParts style all usages in shadowDOM */
border: 5px solid grey;
}
</style>
ShadowDOM is styled by:
<style> within shadowDOM
Inheritable styles
https://lamplightdev.com/blog/2019/03/26/why-is-my-web-component-inheriting-styles/
(cascading) CSS properties
shadowParts (and Themes)
https://meowni.ca/posts/part-theme-explainer/
<slot> are reflected, they are NOT styled by the shadowDOM, but by its container.
See: ::slotted content
(feb 2022) Constructible StyleSheets is still a Chromium only party
https://caniuse.com/mdn-api_cssstylesheet_cssstylesheet

A slightly different approach using observedAttributes to extract setup values...
The logic is like this:
Create a basic <template id="video-player-template"> </template> tag
Re-use the component each time as a <video-player> tag
The video tag values are extracted from the <video-player>'s tag setup code.
Dynamically create a <video> tag object with extracted values from <video-player>.
Here is some testable code:
<html>
<head>
<style>
</style>
</head>
<body>
<!-- 1) create template -->
<template id="video-player-template">
<slot></slot>
</template>
<!-- 2) test as Component -->
<!-- test Component #1 with video loop -->
<video-player id="vidplayer1" width="400" height="300" muted autoplay controls loop type="video/webm"
src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm" >
</video-player>
<!-- test Component #2 -->
<video-player id="vidplayer2" width="200" height="120" muted autoplay controls type="video/webm"
src="https://www.w3schools.com/tags/movie.mp4" >
</video-player>
<!-- controller scripts -->
<script type="text/javascript">
/*
test files
> MP4: https://www.w3schools.com/tags/movie.mp4
> WEBM: https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm"
*/
var template;
var nodes;
var shadowRoot;
customElements.define(
'video-player',
class extends HTMLElement
{
constructor()
{
super();
template = document.getElementById('video-player-template').content;
console.log(template)
shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.appendChild(template.cloneNode(true));
}
//# get component attributes (from template tag setup)
static get observedAttributes()
{
//# extract values from video tag template to use in output video tag
//# eg: controls id width height muted loop autoplay ... etc
return ['src', 'id', 'width', 'height', 'controls', 'muted', 'autoplay', 'loop'];
}
//# attribute change
attributeChangedCallback(property, oldValue, newValue)
{
if (oldValue === newValue) { return; }
else { this[ property ] = newValue; }
}
//# connect component
connectedCallback()
{
//# component is ready to be accessed
//# generate dynamic video tag
let player_code = "";
player_code += `<video `;
if( `${ this.id }` != "undefined")
{ player_code += `id="${ this.id }" `}
if( `${ this.width }` != "undefined")
{ player_code += `width="${ this.width }" `; }
if( `${ this.height }` != "undefined")
{ player_code += `height="${ this.height }" `; }
if( `${ this.controls }` != "undefined")
{ player_code += `controls `; }
if( `${ this.muted }` != "undefined")
{ player_code += `muted `; }
if( `${ this.autoplay }` != "undefined")
{ player_code += `autoplay `; }
if( `${ this.loop }` != "undefined")
{ player_code += `loop `; }
player_code += `<source src="${ this.src }" `;
//# get TYPE for video ( because ".type" is a reserved keyword )
if( String((`${ this.src }`).indexOf(".webm")) != -1)
{ player_code += `type="video/webm" `; }
else if( String((`${ this.src }`).indexOf(".mp4")) != -1)
{ player_code += `type="video/mp4" `; }
player_code += `/> </video> `;
//# apply code of dynamic video tag (add to page)...
this.innerHTML = player_code;
}
});
</script>
</body>
</html>

Related

ASP.Net Core MVC - Bind to List of Strings With Ability To Add/Delete

I want to bind to list of strings with ability to add new item or delete existing, similar to the UI in Azure DevOps -> Process -> Edit Work Item type... it has an a add text box/button at the top, the list of items, and the ability to delete each item with an X.
I tried to look at the html code but it seems dynamically created with javascript. Any existing solution so i don't need to reinvent the wheel? Thank you
According to your description, when the cursor focuses on the input text element, it will show the select items, and might be it implement the autocomplete function.
To achieve this effect, first, you should use JQuery Ajax to get the selectable items from the controller, then, you could attach the focusin, input and keydown events on the input text element, in these events, you could according to the entered value to add html elements, in order to show/hide the select item.
For the delete icon on each select option, you could use the Font Awesome element, and attach the click event to achieve the delete action.
Finally, to achieve the add new value feature, you could use the Bootstrap Modal to show a popup modal and insert the new value.
More detail steps, you could check the following sample code:
Controller:
//main page
public IActionResult SelectIndex()
{
return View();
}
//this method is used to get the select items.
[HttpGet]
public IActionResult GetSelectItems()
{
//initial data. You could query database and get the real data.
List<string> list = new List<string>() { "Angola", "Anguilla", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Cambodia", "Cameroon", "Canada", "Dominica", "Dominican Republic", "Ecuador", "Egypt" };
return Json(list);
}
View page (SelectIndex.cshtml):
CSS style:
<style>
* {
box-sizing: border-box;
}
body {
font: 16px Arial;
}
/*the container must be positioned relative:*/
.autocomplete {
position: relative;
display: inline-block;
}
input {
border: 1px solid transparent;
background-color: #f1f1f1;
padding: 10px;
font-size: 16px;
}
input[type=text] {
background-color: #f1f1f1;
width: 100%;
}
input[type=submit] {
background-color: DodgerBlue;
color: #fff;
cursor: pointer;
}
.autocomplete-items {
position: absolute;
border: 1px solid #d4d4d4;
border-bottom: none;
border-top: none;
z-index: 99;
/*position the autocomplete items to be the same width as the container:*/
top: 100%;
left: 0;
right: 0;
}
.autocomplete-items div {
padding: 10px;
cursor: pointer;
background-color: #fff;
border-bottom: 1px solid #d4d4d4;
}
/*when hovering an item:*/
.autocomplete-items div:hover {
background-color: #e9e9e9;
}
/*when navigating through the items using the arrow keys:*/
.autocomplete-active {
background-color: DodgerBlue !important;
color: #ffffff;
}
</style>
main html resource:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<!--Make sure the form has the autocomplete function switched off:-->
<form autocomplete="off">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="Country">
</div>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
<i class="fa fa-plus"></i> Add Value
</button>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add a New Value</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<input id="inputNewValue" type="text" placeholder="Enter a new Country">
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btnAddNew" data-dismiss="modal">Submit</button>
</div>
</div>
</div>
</div>
</form>
JavaScript script:
<script>
function autocomplete(inp, arr) {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
var currentFocus;
/*execute a function when focus on the text field*/
inp.addEventListener("focusin", function () {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) { arr = countries.slice(0, 5); }
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
b.innerHTML += "<span style='font-size: 1em; color: Tomato; float: right'><i class='fa fa-times'></i></span>"
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function (e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
b.getElementsByTagName("span")[0].addEventListener("click", function (e) {
e.stopPropagation();
var deletevalue = this.parentElement.getElementsByTagName("input")[0].value;
//delete item from the data array.
const index = countries.indexOf(deletevalue);
if (index > -1) {
countries.splice(index, 1);
}
//remove item from current
document.getElementsByClassName("autocomplete-items")[0].removeChild(this.parentElement);
//closeAllLists(e.target);
autocomplete(document.getElementById("myInput"), countries.sort());
});
a.appendChild(b);
}
}
});
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function (e) {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) {return false;}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
b.innerHTML += "<span style='font-size: 1em; color: Tomato; float: right'><i class='fa fa-times'></i></span>"
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function (e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
b.getElementsByTagName("span")[0].addEventListener("click", function (e) {
e.stopPropagation();
var deletevalue = this.parentElement.getElementsByTagName("input")[0].value;
//delete item from the data array.
const index = countries.indexOf(deletevalue);
if (index > -1) {
countries.splice(index, 1);
}
//remove item from current
document.getElementsByClassName("autocomplete-items")[0].removeChild(this.parentElement);
//closeAllLists(e.target);
autocomplete(document.getElementById("myInput"), countries.sort());
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function (e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}
/*An array containing all the country names in the world:*/
// var countries = ["Angola", "Anguilla", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Cambodia", "Cameroon", "Canada", "Dominica", "Dominican Republic", "Ecuador", "Egypt"];
var countries;
$.get("/Home/GetSelectItems", function (response) {
countries = response;
/*initiate the autocomplete function on the "myInput" element, and pass along the countries array as possible autocomplete values:*/
autocomplete(document.getElementById("myInput"), countries.sort());
})
document.getElementById("btnAddNew").addEventListener("click", function (e) {
var newvalue = document.getElementById("inputNewValue").value;
var itemindex = countries.indexOf(newvalue);
if (itemindex == -1) {
countries.push(newvalue);
}
autocomplete(document.getElementById("myInput"), countries.sort());
});
</script>
The result like this (when focus on the input element, it will show the Top 5 items):

VueJS: Why parent components method unable to delete/destroy child's child (`vue2-dropzone`) component entirely?

I am creating a slider in vuejs and am using vue2-dropzone plugin for file uploads where each slide (slide-template.vue) has a vue2-dropzone component.
When app loads, image files are manually added in each vue2-dropzone (manuallyAddFile plugins API) queried from image API (hosted on heroku)
The issue is when I delete the first slide, calling the parent's (slider.vue) method removeSlideFn (passed down to child as prop) from child (slide-template.vue) component first slide is deleted but not entirely the dropzone images of the first slides are not destroyed and remains in the DOM, instead images of slide2, (the next slide) are deleted from the DOM (Pls try it once on codesandbox demo to actually know what I am mean). This does not happen when I delete slide2 or slide3 but only on slide1.
CodeSandBox Demo
App.vue
<template>
<div id="app">
<img width="15%" src="./assets/logo.png">
<slider />
</div>
</template>
<script>
import slider from "./components/slider";
export default {
name: "App",
components: {
slider
}
};
</script>
components\slider.vue (parent)
<template>
<div>
<hooper ref="carousel" :style="hooperStyle" :settings="hooperSettings">
<slide :key="idx" :index="idx" v-for="(slideItem, idx) in slideList">
<slide-template
:slideItem="slideItem"
:slideIDX="idx"
:removeSlideFn="removeCurrSlide" />
</slide>
<hooper-navigation slot="hooper-addons"></hooper-navigation>
<hooper-pagination slot="hooper-addons"></hooper-pagination>
</hooper>
<div class="buttons has-addons is-centered is-inline-block">
<button class="button is-info" #click="slidePrev">PREV</button>
<button class="button is-info" #click="slideNext">NEXT</button>
</div>
</div>
</template>
<script>
import {
Hooper,
Slide,
Pagination as HooperPagination,
Navigation as HooperNavigation
} from "hooper";
import "hooper/dist/hooper.css";
import slideTemplate from "./slide-template.vue";
import { slideShowsRef } from "./utils.js";
export default {
data() {
return {
sliderRef: "SlideShow 1",
slideList: [],
hooperSettings: {
autoPlay: false,
centerMode: true,
progress: true
},
hooperStyle: {
height: "265px"
}
};
},
methods: {
slidePrev() {
this.$refs.carousel.slidePrev();
},
slideNext() {
this.$refs.carousel.slideNext();
},
//Removes slider identified by IDX
removeCurrSlide(idx) {
this.slideList.splice(idx, 1);
},
// Fetch data from firebase
getSliderData() {
let that = this;
let mySliderRef = slideShowsRef.child(this.sliderRef);
mySliderRef.once("value", snap => {
if (snap.val()) {
this.slideList = [];
snap.forEach(childSnapshot => {
that.slideList.push(childSnapshot.val());
});
}
});
}
},
watch: {
getSlider: {
handler: "getSliderData",
immediate: true
}
},
components: {
slideTemplate,
Hooper,
Slide,
HooperPagination,
HooperNavigation
}
};
</script>
components/slide-template.vue (child, with vue2-dropzone)
<template>
<div class="slide-wrapper">
<slideTitle :heading="slideItem.heading" />
<a class="button delete remove-curr-slide" #click="deleteCurrSlide(slideIDX)" ></a>
<vue2Dropzone
#vdropzone-file-added="fileWasAdded"
#vdropzone-thumbnail="thumbnail"
#vdropzone-mounted="manuallyAddFiles(slideItem.zones)"
:destroyDropzone="false"
:include-styling="false"
:ref="`dropZone${ slideIDX }`"
:id="`customDropZone${ slideIDX }`"
:options="dropzoneOptions">
</vue2Dropzone>
</div>
</template>
<script>
import slideTitle from "./slide-title.vue";
import vue2Dropzone from "#dkjain/vue2-dropzone";
import { generate_ObjURLfromImageStream, asyncForEach } from "./utils.js";
export default {
props: ["slideIDX", "slideItem", "removeSlideFn"],
data() {
return {
dropzoneOptions: {
url: "https://vuejs-slider-node-lokijs-api.herokuapp.com/imageUpload",
thumbnailWidth: 150,
autoProcessQueue: false,
maxFiles: 1,
maxFilesize: 2,
addRemoveLinks: true,
previewTemplate: this.template()
}
};
},
components: {
slideTitle,
vue2Dropzone
},
methods: {
template: function() {
return `<div class="dz-preview dz-file-preview">
<div class="dz-image">
<img data-dz-thumbnail/>
</div>
<div class="dz-details">
<!-- <div class="dz-size"><span data-dz-size></span></div> -->
<!-- <div class="dz-filename"><span data-dz-name></span></div> -->
</div>
<div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
<div class="dz-error-message"><span data-dz-errormessage></span></div>
<div class="dz-success-mark"><i class="fa fa-check"></i></div>
<div class="dz-error-mark"><i class="fa fa-close"></i></div>
</div>`;
},
thumbnail: function(file, dataUrl) {
var j, len, ref, thumbnailElement;
if (file.previewElement) {
file.previewElement.classList.remove("dz-file-preview");
ref = file.previewElement.querySelectorAll("[data-dz-thumbnail]");
for (j = 0, len = ref.length; j < len; j++) {
thumbnailElement = ref[j];
thumbnailElement.alt = file.name;
}
thumbnailElement.src = dataUrl;
return setTimeout(
(function(_this) {
return function() {
return file.previewElement.classList.add("dz-image-preview");
};
})(this),
1
);
}
},
// Drag & Drop Events
async manuallyAddFiles(zoneData) {
if (zoneData) {
let dropZone = `dropZone${this.slideIDX}`;
asyncForEach(zoneData, async fileInfo => {
var mockFile = {
size: fileInfo.size,
name: fileInfo.originalName || fileInfo.name,
type: fileInfo.type,
id: fileInfo.id,
childZoneId: fileInfo.childZoneId
};
let url = `https://vuejs-slider-node-lokijs-api.herokuapp.com/images/${
fileInfo.id
}`;
let objURL = await generate_ObjURLfromImageStream(url);
this.$refs[dropZone].manuallyAddFile(mockFile, objURL);
});
}
},
fileWasAdded(file) {
console.log("Successfully Loaded Files from Server");
},
deleteCurrSlide(idx) {
this.removeSlideFn(idx);
}
}
};
</script>
<style lang="scss">
.slide-wrapper {
position: relative;
}
[id^="customDropZone"] {
background-color: orange;
font-family: "Arial", sans-serif;
letter-spacing: 0.2px;
/* color: #777; */
transition: background-color 0.2s linear;
// height: 200px;
padding: 40px;
}
[id^="customDropZone"] .dz-preview {
width: 160px;
display: inline-block;
}
[id^="customDropZone"] .dz-preview .dz-image {
width: 80px;
height: 80px;
margin-left: 40px;
margin-bottom: 10px;
}
[id^="customDropZone"] .dz-preview .dz-image > div {
width: inherit;
height: inherit;
// border-radius: 50%;
background-size: contain;
}
[id^="customDropZone"] .dz-preview .dz-image > img {
width: 100%;
}
[id^="customDropZone"] .dz-preview .dz-details {
color: white;
transition: opacity 0.2s linear;
text-align: center;
}
[id^="customDropZone"] .dz-success-mark,
.dz-error-mark {
display: none;
}
.dz-size {
border: 2px solid blue;
}
#previews {
border: 2px solid red;
min-height: 50px;
z-index: 9999;
}
.button.delete.remove-curr-slide {
padding: 12px;
margin-top: 5px;
margin-left: 5px;
position: absolute;
right: 150px;
background-color: red;
}
</style>
slide-title.vue (not that important)
<template>
<h2 contenteditable #blur="save"> {{ heading }} </h2>
</template>
<script>
export default {
props: ["heading"],
methods: {
save() {
this.$emit("onTitleUpdate", event.target.innerText.trim());
}
}
};
</script>
utils.js (utility)
export async function generate_ObjURLfromImageStream(url) {
return await fetch(url)
.then(response => {
return response.body;
})
.then(rs => {
const reader = rs.getReader();
return new ReadableStream({
async start(controller) {
while (true) {
const { done, value } = await reader.read();
// When no more data needs to be consumed, break the reading
if (done) {
break;
}
// Enqueue the next data chunk into our target stream
controller.enqueue(value);
}
// Close the stream
controller.close();
reader.releaseLock();
}
});
})
// Create a new response out of the stream
.then(rs => new Response(rs))
// Create an object URL for the response
.then(response => {
return response.blob();
})
.then(blob => {
// generate a objectURL (blob:url/<uuid> list)
return URL.createObjectURL(blob);
})
.catch(console.error);
}
Technically this is how the app works, slider.vue loads & fetches data from database (firebase) and stores in a data array slideList, loops over the slideList & passes each slideData (prop slideItem) to vue-dropzone component (in slide-template.vue), when dropzone mounts it fires the manuallyAddFiles(slideItem.zones) on the #vdropzone-mounted custom event.
The async manuallyAddFiles() fetches image from an API (hosted on heroku), creates (generate_ObjURLfromImageStream(url)) a unique blob URL for the image (blob:/) and then calls plugins API dropZone.manuallyAddFile() to load the image into the corresponding dropzone.
To delete the current slide, child's deleteCurrSlide() calls parent's (slider.vue) removeSlideFn (passed as prop) method with the idx of current slide. The removeSlideFn use splice to remove the item at the corresponding array idx this.slideList.splice(idx, 1).
The problem is when I delete the first slide, first slide is deleted but not entirely, the dropzone images of the first slides are not destroyed and still remains in the DOM, instead the images of slide2, (the next slide) are deleted from the DOM.
CodeSandBox Demo
I am not sure what is causing the issue, may it's due to something in the vue's reactivity system OR Vue's Array reactivity caveat that is causing this.
Can anybody pls help me understand & resolve this and if possible point out the reason to the root of the problem.
Your help is much appreciated.
Thanks,
I think you probably missunderstand what is going on:
In VueJS there is a caching method which allow the reusing of existing component generated: - Each of your object are considered equals when rendered (at a DOM level).
So VueJS remove the last line because it is probably ask the least calculation and then recalcul the expected state. There are many side case to this (sometime, the local state is not recalculated). To avoir this: As recommended in the documentation, use :key to trace the id of your object. From the documentation:
When Vue is updating a list of elements rendered with v-for, by default it uses an “in-place patch” strategy. If the order of the data items has changed, instead of moving the DOM elements to match the order of the items, Vue will patch each element in-place and make sure it reflects what should be rendered at that particular index. This is similar to the behavior of track-by="$index" in Vue 1.x.
This default mode is efficient, but only suitable when your list render output does not rely on child component state or temporary DOM state (e.g. form input values).
To give Vue a hint so that it can track each node’s identity, and thus reuse and reorder existing elements, you need to provide a unique key attribute for each item. An ideal value for key would be the unique id of each item. This special attribute is a rough equivalent to track-by in 1.x, but it works like an attribute, so you need to use v-bind to bind it to dynamic values...
new Vue({
el: "#app",
data: {
counterrow: 1,
rows: [],
},
methods: {
addrow: function() {
this.counterrow += 1;
this.rows.push({
id: this.counterrow,
model: ""
});
},
removerows: function(index) {
this.rows.splice(index, 1);
},
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<table>
<tr>
<td><input type="text" name="test1" /></td>
<td><button class="btn" #click="addrow">add row</button></td>
</tr>
<tr v-for="(row,index) in rows" :key="row.id">
<td><input type="text" name="test2" v-model="row.model" /></td>
<td><button class="btn" #click="removerows(index)">remove </button></td>
</tr>
</table>
</div>
In this code:
I corrected the fact counterrow was never incremented
I added a :key
The documentation of :key
What did you mean by
The problem is when I delete the first slide, first slide is deleted but not entirely, the dropzone images of the first slides are not destroyed and still remains in the DOM, instead the images of slide2, (the next slide) are deleted from the DOM.
From what I see, the elements are no longer in the DOM

How to add stripe elements in vue2 from?

In Laravel 5.8 / vuejs 2.6 / vuex / mysql app I need to add stripe elements from https://stripe.com/docs/stripe-js,
http://prntscr.com/phflkd
and for this in resources/views/index.blade.php I added line:
#include('footer')
<script src="{{ asset('js/jquery.min.js') }}"></script>
<script src="{{ asset('js/bootstrap.bundle.min.js') }}"></script>
<script src="{{ asset('js/waves.min.js') }}"></script>
<script src="{{ asset('js/jquery.slimscroll.min.js') }}"></script>
<script src="{{ asset('js/powerange.js') }}"></script>
<script src="{{ asset('js/appInit.js') }}"></script>
<script src="{{ asset('js/app.js') }}{{ "?dt=".time() }}"></script>
<script src="https://js.stripe.com/v3/"></script>
</html>
and in my vue form I init stripe in initStripe() method, which is called in mount event :
<template>
<div class="page-content col-md-offset-2">
<div class="sign-up container-fluid justify-content-center" style="max-width: 460px;">
<hr>
<hr>
<form action="/charge" method="post" id="payment-form">
<div class="form-row">
<label for="card-element">
Credit or debit card
</label>
<div id="card-element">
<!-- A Stripe Element will be inserted here. -->
</div>
<!-- Used to display form errors. -->
<div id="card-errors" role="alert"></div>
</div>
<button>Submit Payment</button>
</form>
<button type="button"
class="btn btn-outline-pink btn-round waves-effect waves-light cancel-btn mr-5" #click.prevent="cancelSelectedSubscription()">
<i :class="getHeaderIcon('cancel')"></i> Cancel
</button>
</div>
</div>
</template>
<script>
import {bus} from '../../../../app';
import appMixin from '../../../../appMixin';
import Vue from 'vue';
export default {
data: function () {
return {
is_page_loaded: false,
}
},
name: 'selectedSubscription',
created() {
if ( typeof this.currentLoggedUser.id != 'number' ) {
this.showPopupMessage("Access", 'Your session is expired !', 'error');
this.$store.commit('logout');
}
this.message = '';
}, // created) {
mounted() {
this.is_page_loaded = true
this.setAppTitle("Selected Subscription", 'Selected Subscription Details', bus);
this.initStripe();
}, // mounted() {
mixins: [appMixin],
methods: {
cancelSelectedSubscription() {
this.$router.push({path: '/personal-details'});
},
initStripe()
{
console.log("Stripe -1::")
// Create a Stripe client.
var stripe = Stripe('pk_test_NNNN');
console.log("Stripe -2::")
// Create an instance of Elements.
var elements = stripe.elements();
console.log("Stripe -3::")
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
color: '#32325d',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
// Create an instance of the card Element.
var card = elements.create('card', {style: style});
console.log("Stripe -4::")
// Add an instance of the card Element into the `card-element` <div>.
card.mount('#card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function (event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
console.log("Stripe -5::")
// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function (event) {
event.preventDefault();
stripe.createToken(card).then(function (result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
this.stripeTokenHandler(result.token);
}
});
});
}, // initStripe() {
// Submit the form with the token ID.
stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
alert( "stripeTokenHandler form::"+var_dump(form) )
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
},
}, // methods: {
computed: {
currentLoggedUser() {
return this.$store.getters.currentLoggedUser;
},
...
} //computed: {
}
</script>
<style lang="css">
/**
* The CSS shown here will not be introduced in the Quickstart guide, but shows
* how you can use CSS to style your Element's container.
*/
.StripeElement {
box-sizing: border-box;
height: 40px;
padding: 10px 12px;
border: 1px solid transparent;
border-radius: 4px;
background-color: white;
box-shadow: 0 1px 3px 0 #e6ebf1;
-webkit-transition: box-shadow 150ms ease;
transition: box-shadow 150ms ease;
}
.StripeElement--focus {
box-shadow: 0 1px 3px 0 #cfd7df;
}
.StripeElement--invalid {
border-color: #fa755a;
}
.StripeElement--webkit-autofill {
background-color: #fefde5 !important;
}
</style>
As result in browser's console I see console messages, “Credit or debit card” label and
uncolored “Submit Payment” button : https://imgur.com/a/TRWc23I
If to click on “Submit Payment” button I see :https://imgur.com/a/CdBSfMC
Is way I added Stripe to my vue form invalid? Which is valid way?
I suppose that I do not have to insert any additive elements/code in this block :
<div id="card-element">
<!-- A Stripe Element will be inserted here. -->
</div>
and they must be uploaded automatically on my form upload ?
and which method have I to use as in my app I save my data with axios?
I made all correctly, it was styles issue.
I replaced css from the example with lines :
#card-element {
line-height: 1.5rem;
margin: 10px;
padding: 10px;
}
.__PrivateStripeElement {
min-width: 300px !important;
min-height: 40px !important;
color: $text_color;
}
and my form was ready for payment!

Changing slider width from px to %

I've built a slider using css, javascript and html. I have a bit of javascript which controls the width and height of the div which contains the slider, as well as the slide speed. However, I want to make the width of the slider 100% of the screen, no matter what size screen. It is currently defined in pixels, but whenever i define it as % it simply disappears. Any ideas or suggestions?
Here is the code
<script type="text/javascript">
$(function() {
$('#one').ContentSlider({
width:1600,
heigth:400,
speed : 800,
easing : 'easeInOutBack'
});
});
</script>
HTML CODE
<title> </title>
<body>
<div id="one" class="contentslider">
<div class="cs_wrapper">
<div class="cs_slider">
<div class="cs_article">
Insert Images Here
</div><!-- End cs_article -->
</div><!-- End cs_slider -->
</div><!-- End cs_wrapper -->
</div><!-- End contentslider -->
<!-- Site JavaScript -->
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="ContentSlider.js"></script>
<script type="text/javascript" src="ContentSlider.js"></script>
<script type="text/javascript">
$(function() {
$('#one').ContentSlider({
width:1600,
heigth:600,
speed : 800,
easing : 'easeInOutBack'
});
});
</script>
<script src="ContentSlider.js" type="text/javascript"></script>
<script src="ContentSlider.js" type="text/javascript"></script>
</body>
CSS CODE
body {
font:80%/1.25em arial, sans-serif;
letter-spacing:.1em;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
margin-left: 0px;
width:100%;
height:100%
}
h1, h2, p, pre {
display:block;
width:99%;
}
.contentslider {
padding:10px; /* This acts as a border for the content slider */
background:#333; /* This is the color of said border */
}
.contentslider {
position:relative;
display:block;
width:100%;
height:100%;
margin:0 auto;
overflow:hidden
}
.cs_wrapper {
position:relative;
display:block;
width:100%;
height:100%;
margin:0;
padding:0;
overflow:hidden;
}
.cs_slider {
position:absolute;
width:10000px;
height:100%;
margin:0;
padding:0;
}
JAVASCRIPT CODE
(function($) {
$.fn.ContentSlider = function(options)
{
var defaults = {
leftBtn : 'cs_leftImg.jpg',
rightBtn : 'cs_rightImg.jpg',
width : '900px',
height : '400px',
speed : 400,
easing : 'easeOutQuad',
textResize : false,
IE_h2 : '26px',
IE_p : '11px'
}
var defaultWidth = defaults.width;
var o = $.extend(defaults, options);
var w = parseInt(o.width);
var n = this.children('.cs_wrapper').children('.cs_slider').children('.cs_article').length;
var x = -1*w*n+w; // Minimum left value
var p = parseInt(o.width)/parseInt(defaultWidth);
var thisInstance = this.attr('id');
var inuse = false; // Prevents colliding animations
function moveSlider(d, b)
{
var l = parseInt(b.siblings('.cs_wrapper').children('.cs_slider').css('left'));
if(isNaN(l)) {
var l = 0;
}
var m = (d=='left') ? l-w : l+w;
if(m<=0&&m>=x) {
b
.siblings('.cs_wrapper')
.children('.cs_slider')
.animate({ 'left':m+'px' }, o.speed, o.easing, function() {
inuse=false;
});
if(b.attr('class')=='cs_leftBtn') {
var thisBtn = $('#'+thisInstance+' .cs_leftBtn');
var otherBtn = $('#'+thisInstance+' .cs_rightBtn');
} else {
var thisBtn = $('#'+thisInstance+' .cs_rightBtn');
var otherBtn = $('#'+thisInstance+' .cs_leftBtn');
}
if(m==0||m==x) {
thisBtn.animate({ 'opacity':'0' }, o.speed, o.easing, function() { thisBtn.hide(); });
}
if(otherBtn.css('opacity')=='0') {
otherBtn.show().animate({ 'opacity':'1' }, { duration:o.speed, easing:o.easing });
}
}
}
function vCenterBtns(b)
{
// Safari and IE don't seem to like the CSS used to vertically center
// the buttons, so we'll force it with this function
var mid = parseInt(o.height)/2;
b
.find('.cs_leftBtn img').css({ 'top':mid+'px', 'padding':0 }).end()
.find('.cs_rightBtn img').css({ 'top':mid+'px', 'padding':0 });
}
return this.each(function() {
$(this)
// Set the width and height of the div to the defined size
.css({
width:o.width,
height:o.height
})
// Add the buttons to move left and right
.prepend('<img src="'+o.leftBtn+'" />')
.append('<img src="'+o.rightBtn+'" />')
// Dig down to the article div elements
.find('.cs_article')
// Set the width and height of the div to the defined size
.css({
width:o.width,
height:o.height
})
.end()
.find('.cs_leftBtn')
.css('opacity','0')
.hide()
.end()
.find('.cs_rightBtn')
.hide()
.animate({ 'width':'show' });
if(o.textResize===true) {
var h2FontSize = $(this).find('h2').css('font-size');
var pFontSize = $(this).find('p').css('font-size');
$.each(jQuery.browser, function(i) {
if($.browser.msie) {
h2FontSize = o.IE_h2;
pFontSize = o.IE_p;
}
});
$(this).find('h2').css({ 'font-size' : parseFloat(h2FontSize)*p+'px', 'margin-left' : '66%' });
$(this).find('p').css({ 'font-size' : parseFloat(pFontSize)*p+'px', 'margin-left' : '66%' });
$(this).find('.readmore').css({ 'font-size' : parseFloat(pFontSize)*p+'px', 'margin-left' : '66%' });
}
var leftBtn = $(this).children('.cs_leftBtn');
leftBtn.bind('click', function() {
if(inuse===false) {
inuse = true;
moveSlider('right', leftBtn);
}
return false;
});
var rightBtn = $(this).children('.cs_rightBtn');
rightBtn.bind('click', function() {
if(inuse===false) {
inuse=true;
moveSlider('left', rightBtn);
}
return false;
});
vCenterBtns($(this));
});
}
})(jQuery)
You could change width to $(this).parent().innerWidth(), but that will only work on init, if the user resizes it will not change. This is because the plugin only sets a size on init
Might be a better idea to search for a fullwidth slider, these often fix some issues which arrise with fullwidths and resizing

Map won't show right in Joomla

I have the following code of a map using api google, I have tested the code in several html editor and its work perfectly, but when i upload in my web page doesn’t work. The map appears all zoomed in some random point in the ocean. I create an article in Joomla 1.5.20, paste the code. Its shows right in the preview but not in the web page. I disable filtering and use none editor and still won’t work. Thanks for the help.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBInlv7FuwtKGhzBP0oISDoB2Iu79HNrPU&sensor=false">
</script>
<script type="text/javascript">
var map;
// lets define some vars to make things easier later
var kml = {
a: {
name: "Productor",
url: "https://maps.google.hn/maps/ms?authuser=0&vps=2&hl=es&ie=UTF8&msa=0&output=kml&msid=200984447026903306654.0004c934a224eca7c3ad4"
},
b: {
name: "A&S",
url: "https://maps.google.hn/maps/ms?ie=UTF8&authuser=0&msa=0&output=kml&msid=200984447026903306654.0004c94bac74cf2304c71"
}
// keep adding more if ye like
};
// initialize our goo
function initializeMap() {
var options = {
center: new google.maps.LatLng(13.324182,-87.080071),
zoom: 9,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
map = new google.maps.Map(document.getElementById("map_canvas"), options);
var ctaLayer = new google.maps.KmlLayer('https://maps.google.hn/maps/ms?authuser=0&vps=5&hl=es&ie=UTF8&oe=UTF8&msa=0&output=kml&msid=200984447026903306654.0004c94bc3bce6f638aa1');
ctaLayer.setMap(map);
var ctaLayer = new google.maps.KmlLayer('https://maps.google.hn/maps/ms?authuser=0&vps=2&ie=UTF8&msa=0&output=kml&msid=200984447026903306654.0004c94ec7e838242b67d');
ctaLayer.setMap(map);
createTogglers();
};
google.maps.event.addDomListener(window, 'load', initializeMap);
// the important function... kml[id].xxxxx refers back to the top
function toggleKML(checked, id) {
if (checked) {
var layer = new google.maps.KmlLayer(kml[id].url, {
preserveViewport: true,
suppressInfoWindows: true
});
google.maps.event.addListener(layer, 'click', function(kmlEvent) {
var text = kmlEvent.featureData.description;
showInContentWindow(text);
});
function showInContentWindow(text) {
var sidediv = document.getElementById('content_window');
sidediv.innerHTML = text;
}
// store kml as obj
kml[id].obj = layer;
kml[id].obj.setMap(map);
}
else {
kml[id].obj.setMap(null);
delete kml[id].obj;
}
};
// create the controls dynamically because it's easier, really
function createTogglers() {
var html = "<form><ul>";
for (var prop in kml) {
html += "<li id=\"selector-" + prop + "\"><input type='checkbox' id='" + prop + "'" +
" onclick='highlight(this,\"selector-" + prop + "\"); toggleKML(this.checked, this.id)' \/>" +
kml[prop].name + "<\/li>";
}
html += "<li class='control'><a href='#' onclick='removeAll();return false;'>" +
"Limpiar el Mapa<\/a><\/li>" +
"<\/ul><\/form>";
document.getElementById("toggle_box").innerHTML = html;
};
// easy way to remove all objects
function removeAll() {
for (var prop in kml) {
if (kml[prop].obj) {
kml[prop].obj.setMap(null);
delete kml[prop].obj;
}
}
};
// Append Class on Select
function highlight(box, listitem) {
var selected = 'selected';
var normal = 'normal';
document.getElementById(listitem).className = (box.checked ? selected: normal);
};
</script>
<style type="text/css">
.selected { font-weight: bold; }
</style>
</head>
<body>
<div id="map_canvas" style="width: 80%; height: 400px; float:left"></div>
<div id="toggle_box" style="position: absolute; top: 100px; right: 640px; padding: 10px; background: #fff; z-index: 5; "></div>
<div id="content_window" style="width:10%; height:10%; float:left"></div>
</body>
</html>
The problem was solve using dropbox to host the KML files insted google maps.