How can I trigger modal boxes using the following javascript code? - javascript

Hey guys I need just a little bit of help with this.
So I have modal boxes hiding on my page and when I click on them using the video platform VERSE they work perfectly.
My questions is: How can I call the same modal boxes if I wan to call them from a regular link or button on the page.
Here is the sample:
http://digitalfeast.com/clients/nccv/ncc-verse.html
Here is my Javascript code:
(function() {
(function() {
window.onload = function() {
var frame = document.getElementsByName("verse-iframe")[0].contentWindow;
// Variables below (i.e. "menu-1") reference div id from your markup
function receiveMessage(event) {
var data = (typeof event.data === "String") ? JSON.parse(event.data) : event
var modalWindow1 = document.getElementById("ruben-1");
var modalWindow2 = document.getElementById("ruben-2");
var modalWindow3 = document.getElementById("menu-3");
var modalWindow4 = document.getElementById("menu-4");
// Variables below (i.e. "menu-1") reference the unique callback names entered for your hotspots in the Verse editor
if (data.data["identifier"] === "ruben-1") {
modalWindow1.style.display = "block";
}
if (data.data["identifier"] === "ruben-2") {
modalWindow2.style.display = "block";
}
if (data.data["identifier"] === "menu-3") {
modalWindow3.style.display = "block";
}
if (data.data["identifier"] === "menu-4") {
modalWindow4.style.display = "block";
}
}
var closeBtns = document.getElementsByClassName("modal-close");
for (var i = 0; i < closeBtns.length; i++) {
var btn = closeBtns[i];
btn.onclick = function (event) {
event.target.parentNode.parentNode.style.display = "none";
frame.postMessage({action: "play"}, "*");
};
}
window.addEventListener('message', receiveMessage);
var frame = document.getElementsByName("verse-iframe")[0].contentWindow;
};
}());
}());

Given your code, all you need to do is send the window a message using the Messaging API inside your button click handler.
Your event listener will then execute the receiveMessage function and open your model for ruben-1.
window.onload = () => {
document.querySelector('[data-modal="ruben-1"]').addEventListener("click", (e) => {
let postData = {
identifier: e.target.dataset.modal
};
window.postMessage(postData, "*");
});
window.addEventListener('message', m => {
alert(m.data.identifier);
});
}
<button data-modal="ruben-1">Ruben-1 Video</button>

Related

I can't stop executing a function

My problem is that I can't stop executing a function and it is causing me a big problem. This function is a function that I perform when the modal is opened and it is waiting for me to submit the form to register or update the data. The problem is that every time I close and open this modal, it executes the function depending on how many times I opened this modal. For example: if I open the modal for the first time, register and close. If I open it again, it will register the value I enter and it will register again but an empty data. My code is a bit long because I split it up to be able to optimize it. I'm using the "realtime database", from firebase
This is the code for the floating buttons. I click on a button and it shows another two buttons, one for registering categories and another for products. Clicking on any of them opens a specific modal
function modalFloatButtons_options() {
let floatButtonAdd = document.getElementById("carte_modalFloatAddBtn");
let modalFloatButtonsOptions = document.querySelector(".modalFloatButtons_options");
modalFloatButtonsOptions.style.display = "none";
// Functions
// Open or close div
function openCloseOptions() {
floatButtonAdd.addEventListener("click", (e) => {
if(modalFloatButtonsOptions.style.display == "none"){
modalFloatButtonsOptions.style.display = "block";
optionsAnimation_openClose("block");
modalFloatButton_options_btnsEnvetListener()
}else{
optionsAnimation_openClose("none");
setTimeout(() => {
modalFloatButtonsOptions.style.display = "none";
}, 251);
}
})
}openCloseOptions()
// Options animation
function optionsAnimation_openClose(display) {
if(display == "block"){
modalFloatButtonsOptions.animate([
{ bottom: '10%' },
{ bottom: '120%' }
], {
duration: 250,
})
}else{
modalFloatButtonsOptions.animate([
{ bottom: '120%' },
{ bottom: '0%' }
], {
duration: 250,
})
}
}
// Float buttons - options - event listener
function modalFloatButton_options_btnsEnvetListener() {
let modalFloatButtonOptionsBtn = document.querySelectorAll(".modalFloatButtons_options_btn");
modalFloatButtonOptionsBtn.forEach(element => {
element.addEventListener("click", (e) => {
modal_openModal(e.target.id.substr(4), "create")
})
});
}
}modalFloatButtons_options()
// Open modal
function modal_openModal(id, method, data, key) {
let div = document.getElementById(id);
div.style.display = "flex";
modal_closeModal(div, id);
if(id == "modalCategory"){
modalAddCategory("execute", method, data, key)
}else if(id == "modalProduct"){
}
}
// Close modal
function modal_closeModal(div, id) {
let closeBtn = document.querySelector("#"+id+" .modal_closeBtn");
div.addEventListener("click", (e) => {
if(e.target.id === div.id || e.target.classList[1] === "modal_closeBtn"){
div.style.display = "none";
modalAddCategory("break")
}
})
}
When he clicks the button, he will see the id and execute the function
function modalAddCategory(execute, method, updateData, key){
let form = document.querySelector("#modalCategory form");
let submitbtn = document.querySelector("#modalCategory form button");
let categoryInput = document.querySelector("#modalCategory form input[name='categoryTitle']");
// Putting value in the input if it is for update
if(method == "update"){
categoryInput.value = updateData.category
}
console.log(method)
console.log("--------")
// Event listener - submit btnm
realtimedb_eventSubmitBtn(submitbtn, categoryData, form);
// Data
function categoryData() {
let data = {
category: categoryInput.value
};
// Register data
if(method == "update"){
realtimedb_update("Categories", data, key)
}else if(method == "create") {
realtimedb_create("Categories", data);
}
}
}
And it is and the function that is giving me trouble
// Event listener - submit btn
function realtimedb_eventSubmitBtn(btn, nameFunction, form) {
btn.addEventListener("click", (element) => {
element.preventDefault();
nameFunction();
form.reset();
})
}
I tried to use return but it didn't work, someone please help me

How To Stop all Functions in JavaScript using an IF Function

I'm trying to use one function and a lot of IF functions to run this code.
I'm going to make this as a note app.
I want to add an IF function that has an class called stop-note.
I want to add it in the notes list for it's IF function then I want to add it to the "renderNotes" for it's link like style.
notesList.on('click', function (e) {
e.preventDefault();
var target = $(e.target);
var abort = false;
// Listen to the selected note.
if (target.hasClass('listen-note')) {
if (abort) {
return;
}
var content = target.closest('.note').find('.content').text();
readOutLoud(content);
}
//Edit Note
if (target.hasClass('edit-note')) {
editText(content);
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
var content = target.closest('.note').find('.content').text();
}
// Delete note.
if (target.hasClass('delete-note')) {
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
}
});
This is my function that runs my function above.
function renderNotes(notes) {
var html = '';
if (notes.length) {
notes.forEach(function (note) {
html += `<li class="note">
<p class="header">
<span class="date">${note.date}</span>
Listen
Edit
html = <button class="stop-note" onclick="abort = true">Stop</button>
Delete
</p>
<p class="content">${note.content}</p>
</li>`;
});
} else {
html = '<li><p class="content">You don\'t have any notes yet.</p></li>';
}
notesList.html(html);
}
abort is a local variable, and you set it to false whenever they click on a note list. So onclick="abort = true" has no effect on the variable that's being tested in the function.
You need to make it a global variable.
window.abort = false;
notesList.on('click', function (e) {
e.preventDefault();
var target = $(e.target);
// Listen to the selected note.
if (target.hasClass('listen-note')) {
if (abort) {
return;
}
var content = target.closest('.note').find('.content').text();
readOutLoud(content);
}
//Edit Note
if (target.hasClass('edit-note')) {
editText(content);
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
var content = target.closest('.note').find('.content').text();
}
// Delete note.
if (target.hasClass('delete-note')) {
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
}
});

Javascript classes and Customevents

I want to know how to add a custom event to a instance of a class and call it for that instance.
My code right now:
var event = document.createEvent('event');
event.initEvent('build', true, true);
class link {
constructor(Href, Text = "Click me", Target = "__blank") {
this.href = Href;
this.text = Text
this.target = Target;
this.eventElm = document.createElement("event");
//this.event = document.createEvent('event');
//this.event.initEvent('build', true, true);
}
}
class creator {
constructor(Objs) {
for(var i in Objs) {
window.document.body.innerHTML += ""+Objs[i].text+"<br>";
if(Objs[i].href == "#") {
Objs[i].eventElm.dispatchEvent(event);
}
}
}
}
var l = new link("#");
var lo = new link("#");
var ar = [];
ar.push(l);
ar.push(lo);
l.eventElm.addEventListener('build', function(e) {
console.log(e);
}, false);
//l.eventElm.dispatchEvent(event);
window.onload = function () {
var crea = new creator(ar);
console.log(l.href);
}
This code returns the error
eventtest.html:24 Uncaught DOMException: Failed to execute 'dispatchEvent' on 'EventTarget': The event is already being dispatched.
at new creator (http://localhost/eventtest.html:24:25)
at window.onload (http://localhost/eventtest.html:44:16)
I want to do this in plain javascript no jquery. Thanks for taking the time to read this and hopefully help me.
You're declaring a global event variable. But most browsers (IE, Edge, Chrome) already have a global event variable (the currently-being-dispatched event). So you end up trying to re-dispatch the load event that's being handled.
This is one of the many reasons not to put your code at global scope. Instead, wrap it in a scoping function:
(function() {
// Your code here...
})();
Now, your event variable isn't conflicting with the global event.
Live Example:
(function() {
var event = document.createEvent('event');
event.initEvent('build', true, true);
class link {
constructor(Href, Text = "Click me", Target = "__blank") {
this.href = Href;
this.text = Text
this.target = Target;
this.eventElm = document.createElement("event");
//this.event = document.createEvent('event');
//this.event.initEvent('build', true, true);
}
}
class creator {
constructor(Objs) {
for(var i in Objs) {
window.document.body.innerHTML += ""+Objs[i].text+"<br>";
if(Objs[i].href == "#") {
Objs[i].eventElm.dispatchEvent(event);
}
}
}
}
var l = new link("#");
var lo = new link("#");
var ar = [];
ar.push(l);
ar.push(lo);
l.eventElm.addEventListener('build', function(e) {
console.log(e);
}, false);
//l.eventElm.dispatchEvent(event);
window.onload = function () {
var crea = new creator(ar);
console.log(l.href);
}
})();
Separately: You probably want to create a new event object each time you dispatch your event, rather than having that single global-to-your-code event variable.

Windows Store Javascript background audio tassk close() method?

I have created a simple Windows 8.1 store app for just playing internet streaming radio. It looks and works good, but I can't upload my app to Windows Store! After validation a get the message like:
WinJS background task
Error Found:
The WinJS background tasks test encountered the
following errors:
App Radio Skovoroda did not call close() in the
background task JavaScript code found in file default.html.
Impact if not fixed: Apps with background tasks that do not call close() can result in draining the battery.
How to fix: Update the background
task to call close().
The point is I do not need to call close(), because it is a radio player, so, it must play in background for a long time! Any ideas? How to do my app pass the validator?
My script code:
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application was suspended and then terminated.
// To create a smooth user experience, restore application state here so that it looks like the app never stopped running.
}
args.setPromise(WinJS.UI.processAll());
var buttonMediaControl = document.getElementById("mediaControlButton");
buttonMediaControl.addEventListener("click", playAndStop, false);
//add variables for social buttons
//Facebook
var fbButton = document.getElementById("fbButton");
fbButton.addEventListener("click", goToFbPage, false);
//VKotakte
var vkButton = document.getElementById("vkButton");
vkButton.addEventListener("click", goToVkPage, false);
//Twitter
var twButton = document.getElementById("twButton");
twButton.addEventListener("click", goToTwPage, false);
//Instagram
var igButton = document.getElementById("igButton");
igButton.addEventListener("click", goToIgPage, false);
//YouTube
var ytButton = document.getElementById("ytButton");
ytButton.addEventListener("click", goToYtPage, false);
//TuneIn
var tiButton = document.getElementById("tiButton");
tiButton.addEventListener("click", goToTiPage, false)
// Assign the button object to MediaControls
var systemMediaControls = Windows.Media.SystemMediaTransportControls.getForCurrentView();
systemMediaControls.addEventListener("buttonpressed", systemMediaControlsButtonPressed, false);
systemMediaControls.isPlayEnabled = true;
systemMediaControls.isPauseEnabled = true;
systemMediaControls.isStopEnabled = true;
systemMediaControls.playbackStatus = Windows.Media.MediaPlaybackStatus.closed;
}
};
app.oncheckpoint = function (args) {
};
// Plays the media.
function playMedia() {
var media = document.getElementById("skovorodaStreamingAudio");
media.play();
var statusIcon = document.getElementById("playStopImage");
statusIcon.src = "images/skovoroda_stop_button.png";
var systemMediaControls = Windows.Media.SystemMediaTransportControls.getForCurrentView();
systemMediaControls.playbackStatus = Windows.Media.MediaPlaybackStatus.playing;
}
// Pauses the media.
function pauseMedia() {
var media = document.getElementById("skovorodaStreamingAudio");
media.pause();
var statusIcon = document.getElementById("playStopImage");
statusIcon.src = "images/skovoroda_play_button.png";
var systemMediaControls = Windows.Media.SystemMediaTransportControls.getForCurrentView();
systemMediaControls.playbackStatus = Windows.Media.MediaPlaybackStatus.paused;
}
// Stops the media.
function stopMedia() {
var media = document.getElementById("skovorodaStreamingAudio");
media.pause();
media.currentTime = 0;
}
function playAndStop() {
var myAudio = document.getElementById("skovorodaStreamingAudio");
var statusIcon = document.getElementById("playStopImage");
if (myAudio.paused) {
var systemMediaControls = Windows.Media.SystemMediaTransportControls.getForCurrentView();
systemMediaControls.playbackStatus = Windows.Media.MediaPlaybackStatus.playing;
myAudio.play();
statusIcon.src = "images/skovoroda_stop_button.png";
} else {
var systemMediaControls = Windows.Media.SystemMediaTransportControls.getForCurrentView();
systemMediaControls.playbackStatus = Windows.Media.MediaPlaybackStatus.paused;
myAudio.pause();
statusIcon.src = "images/skovoroda_play_button.png";
}
}
// The media Play event handler.
function mediaPlaying() {
// Update the SystemMediaTransportControl state.
systemMediaControls.playbackStatus = Windows.Media.MediaPlaybackStatus.playing;
}
// The media Pause event handler.
function mediaPaused() {
// Update the SystemMediaTransportControl state.
systemMediaControls.playbackStatus = Windows.Media.MediaPlaybackStatus.paused;
}
// The media Ended event handler.
function mediaEnded() {
// Update the SystemMediaTransportControl state.
systemMediaControls.playbackStatus = Windows.Media.MediaPlaybackStatus.stopped;
}
function goToFbPage() {
window.open("https://www.facebook.com/radioskovoroda?__mref=message_bubble");
}
function goToVkPage() {
window.open("https://vk.com/radioskovoroda");
}
function goToTwPage() {
window.open("https://twitter.com/RadioSkovoroda");
}
function goToIgPage() {
window.open("https://instagram.com/radioskovoroda");
}
function goToYtPage() {
window.open("https://www.youtube.com/channel/UCSgkIdg5MztN_2z9q_8u3Nw")
}
function goToTiPage() {
window.open("http://tunein.com/radio/radio-skovoroda-s248591/")
}
// Event handler for SystemMediaTransportControls' buttonpressed event
function systemMediaControlsButtonPressed() {
if (Windows.Media.MediaControl.isPlaying === true) {
pauseMedia();
} else {
playMedia();
}
}
app.start();
})();

Close an injected iframe

I have a content script that runs from my chrome extension.
this script injects an iframe to the body of the current page.
i want to have the possibility to close the iframe from within the iframe.
how do i do this?
when i searched this issue on the web, almost each solution uses the window.parent.document property which for some reason is undefined in my case. any ideas?
EDIT - Code Sample:
in the HTML of the iframe:
<script type="text/javascript">
function frameClose() {
var windowFrames = window.parent.frames;
for (var i = 0; i < windowFrames.length; i++) {
var aFrame = windowFrames[i];
if (aFrame.name == 'myFrame') {
alert('in frame');
// WHAT TO DO HERE?
// window.parent.document is undefined
// aFrame.parentNode.removeChild(aFrame); - THIS DOES NOT WORK ALSO
break;
}
}
}
</script>
this is how i inject the iframe:
Extension.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {
file : "/js/PushIFrame.js"
}, function() {
if (chrome.extension.lastError) {
}
});
});
and in PushIFrame.js i have:
chrome.extension.sendMessage({
action: "pushFrame",
source: pushIframe(document)
});
function pushIframe(document) {
var existingFrame = document.getElementById('bmarkFrame');
if (existingFrame == null) {
var temp = document.createElement('iframe');
temp.id = 'myFrame';
temp.name = 'myFrame';
temp.setAttribute('scrolling', 'no');
temp.setAttribute('allowtransparency', 'true');
temp.style.border = 'none';
temp.style.height = '100%';
temp.style.width = '100%';
temp.style.position = 'fixed';
temp.style.zIndex = 99999999;
temp.style.top = 0;
temp.style.left = 0;
temp.style.display = 'block';
temp.src = 'https://www.mysite.com/';
document.body.appendChild(temp);
}
else {
existingFrame.style.display = 'block';
}
}
Let the content script (say PushIframe.js) bind a message event to the main frame. Then, whenever you want to hide the iframe, call parent.postMessage to notify the main frame. This message is received by the content script, from where you can hide the frame (as defined in your function pushIframe).
// PushIframe.js:
addEventListener('message', function(ev) {
if (ev.data === 'closeIframe') {
pushIframe(document); // Your code
}
});
// Iframe:
<script>
function frameClose() {
parent.postMessage('closeIframe', '*');
}
</script>

Categories