javascript multiple functions at once - javascript

As I needed help here
#ryanpcmcquen offered great help, but as a "noob" at javascript I would like to know 2 more things
When I want to create another function how do I make it?
document.addEventListener('DOMContentLoaded', function () {
'use strict';
var unitBlock = document.querySelector('select#unit_block');
var unitRowBig = document.querySelector('select#unit_row_big');
var unitRow = document.querySelector('select#unit_row');
var unitColumn = document.querySelector('select#unit_column');
var unitSize = document.querySelector('select#unit_size');
unitBlock.addEventListener('change', function () {
if (unitBlock.value === 'A') {
unitRowBig.disabled = false;
unitRowBig[4].disabled = false;
} else {
unitRowBig.disabled = false;
unitRowBig[4].disabled = true;
}
});
unitBlock.addEventListener('change1', function () {
if ((unitRowBig.value === '1') && (unitBlock.value === 'A')) {
unitRow.disabled = false;
unitRow[8].disabled = true;
unitRow[9].disabled = true;
unitRow[10].disabled = true;
unitRow[11].disabled = true;
unitRow[12].disabled = true;
}
});
});
Because it doesn't seems to work my way.

No need to add a new event, besides change1 is not a valid event, you can find a list of events here:
https://developer.mozilla.org/en-US/docs/Web/Events
Just put that conditional inside the original event handler:
document.addEventListener('DOMContentLoaded', function () {
'use strict';
var unitBlock = document.querySelector('select#unit_block');
var unitRowBig = document.querySelector('select#unit_row_big');
var unitRow = document.querySelector('select#unit_row');
var unitColumn = document.querySelector('select#unit_column');
var unitSize = document.querySelector('select#unit_size');
unitBlock.addEventListener('change', function () {
// You may want to comment out all of this section:
if (unitBlock.value === 'A') {
unitRowBig.disabled = false;
unitRowBig[4].disabled = false;
} else {
unitRowBig.disabled = false;
unitRowBig[4].disabled = true;
}
// Down to here.
// Here's your code!
if ((unitRowBig.value === '1') && (unitBlock.value === 'A')) {
unitRow.disabled = false;
unitRow[8].disabled = true;
unitRow[9].disabled = true;
unitRow[10].disabled = true;
unitRow[11].disabled = true;
unitRow[12].disabled = true;
// Including an antithetical clause,
// to account for the user changing their mind.
} else {
unitRow.disabled = true;
unitRow[8].disabled = false;
unitRow[9].disabled = false;
unitRow[10].disabled = false;
unitRow[11].disabled = false;
unitRow[12].disabled = false;
}
});
});
Note that I also included the opposite disabled conditions in an else clause, in case the user makes one choice, and then changes to another.

In case you really need two separate functions (what is not the case here), just do it like this:
unitBlock.addEventListener('change', function () {
console.log('First event listener')
});
unitBlock.addEventListener('change', function () {
console.log('Second event listener')
});
document.addEventListener stores all the functions you sent to him, so when the change event will be fired, it will execute all of them, in the order you passed them to it.
In short, when the change event is fired, you will have:
> "First event listener"
> "Second event listener"
I hope this helped you!

Related

Preventing Jquery .click toggle function from running over and over with excess clicking

Im building a .clicktoggle function in jQuery and for the life of me i can't get a .stop like effect on it, basically i don't want it to play over and over if mash clicked.
I want it to be applied the the function so its self contained, that's where im stuck.
JS fiddle link
(function($) {
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
}(jQuery));
$('div').clickToggle(function() {
$('.testsubject').fadeOut(500);
}, function() {
$('.testsubject').fadeIn(500);
});
<div class="clickme">click me fast</div>
<div class="testsubject">how do i stop it playing over and over if you click alot</div>
Toggle .click seems like something alot of people would use so i thought it might be useful to ask it here
By adding a check to a boolean variable fadeInProgress, you can choose to only queue the animation if fadeInProgress is false. It then sets the value to true and executes the animation. When the animation is completed, set the value to false.
var fadeInProgress = false;
$('div').clickToggle(function() {
if (!fadeInProgress) {
fadeInProgress = true;
$('.testsubject').fadeOut(700, function(){fadeInProgress = false;});
}
}, function() {
if (!fadeInProgress) {
fadeInProgress = true;
$('.testsubject').fadeIn(700, function(){fadeInProgress = false;});
}
});
var clicked = false;
var doing = false;
$(".clickme").click(function(e) {
if (doing) {
return;
} else {
doing = true;
}
doing = true;
clicked = !clicked;
if (clicked) {
$('.testsubject').fadeOut(700, function() {
doing = false
});
} else {
$('.testsubject').fadeIn(700, function() {
doing = false;
});
}
});
This example is a simple toggle which only allows you to click when it is not doing anything. I explained on IRC, but as an example here, the function only runs when doing is set to false, which only happens when it's set after fadeIn() or fadeOut's callback function thingymajigger.

WinJS listview iteminvokedHanlder how to

I'm using the iteminvokedHandler and was wonder if there is a better way to interact with the listView.
Currently using this:
WinJS.UI.processAll(root).then(function () {
var listview = document.querySelector('#myNotePad').winControl;
listview.addEventListener("iteminvoked", itemInvokedHandler,false);
function itemInvokedHandler(e) {
e.detail.itemPromise.done(function (invokedItem) {
myEdit();
});
};
});
The problem is that everytime I click on the listview myEdit() is run and propagates within the listview. I was wondering how to do it once and stop invoking listview until I am done with myEdit? Is there a simpler way to handle such a situation as this?
Simple yet hard to see when you have a mind block and forget some of the basics (yes yes I'm still learning):
var testtrue = true;
WinJS.UI.processAll(root).then(function () {
var listview = document.querySelector('#myNotePad').winControl;
listview.addEventListener("iteminvoked", itemInvokedHandler,false);
function itemInvokedHandler(e) {
e.detail.itemPromise.done(function (invokedItem) {
if (testtrue === true){
myEdit();
}
});
};
});
In myEdit:
function myEdit() {
var theelem = document.querySelector(".win-selected #myNotes");
var gestureObject = new MSGesture();
gestureObject.target = theelem;
theelem.gestureObject = gestureObject;
theelem.addEventListener("pointerdown", pointerDown, false);
theelem.addEventListener("MSGestureHold", gestureHold, false);
function pointerDown(e) {
e.preventDefault();
e.target.gestureObject.addPointer(e.pointerId);
}
function gestureHold(e) {
if (e.detail === e.MSGESTURE_FLAG_BEGIN && test === true) {
e.preventDefault();
editNotes();
} else {
}
console.log(e);
}
theelem.addEventListener("contextmenu", function (e) {
e.preventDefault();}, false); //Preventing system menu
};
function editNotes() {
//The Code I wish to execute
return test = false;
};
What I needed was a conditional statement so that it would run if true and not if false. That same test needed to be done in the gestureHold otherwise it would continue to fire myEdit on the invoked item because of the way the gesture is attached to the item the first time it is run.

AngularJS $scope.$on multiple events

I have a scenario when I need to listen to 2 different events transmitted via $scope.$emit and I want to act only when both have happened.
So for example if the events triggering is the following:
$scope.$emit('first');
// do nothing
$scope.$emit('second');
// execute something
$scope.$emit('first');
// Do nothing
$scope.$emit('first');
// Do nothing
$scope.$emit('second');
// execute something
Is there anything that does it out of the box? Ideally like
$scope.$on('first', 'second', function() {});
I've considered doing the following:
var triggeredEvents = [];
$scope.$on('first', function() {
notifyEventTriggered('first');
});
$scope.$on('second', function() {
notifyEventTriggered('second');
});
function notifyEventTriggered(event) {
if (triggeredEvents.indexOf(event) == -1) {
triggeredEvents.push(event);
}
if (triggeredEvents.length > 1) {
execute();
triggeredEvents.length = 0;
}
}
So is there something that does it simpler? Or some suggestions on how to improve it? Other than creating a service for this.
Thanks
There's no built in way to do it. I would personally attach a new method to $rootScope like this:
https://jsfiddle.net/qv6m2drz/5/
var app = angular.module('jsbin', []);
app.run(['$rootScope', function($rootScope) {
$rootScope.onAllEvents = (function() {
var watchedEvents = {};
return onAllEvents;
/*
* Attach listeners to all events
*/
function onAllEvents(events, fn){
if(!events || !events.length) return ;
events.forEach(function(evt){
watchedEvents[evt] = false;
this.$on(evt, function(){
watchedEvents[evt] = true;
tryExecute(fn);
});
}.bind(this));
}
/*
* Check if all `watchedEvents` have fired. If yes, run fn() and reset the events
*/
function tryExecute(fn){
var shouldExecute = true;
for(evt in watchedEvents){
if(watchedEvents.hasOwnProperty(evt) && !watchedEvents[evt]){
shouldExecute = false;
}
}
if(shouldExecute){
fn();
for(evt in watchedEvents){
if(watchedEvents.hasOwnProperty(evt)){
watchedEvents[evt] = false;
}
}
}
}
})();
}]);

How can I determine when two object is loaded?

I'm loading an image
obgImage.onload = function ( imageReady = true )
document.getElementById('vimeo').onload= function() {
videoReady = true;
}
What should i use to recognize when both of these are ready?
if(videoReady == true && pageReady == true){
$('#loading').fadeOut();
}
how do i make the if statement constantly check? I have query
var videoReady = false,
imageReady = false,
_ready = function() {
if (videoReady && imageReady) {
// do your code
}
else {
// waiting for the other onload function to be called
}
};
obgImage.onload = function () {
imageReady = true;
_ready();
};
document.getElementById('vimeo').onload= function() {
videoReady = true;
_ready();
};
Using this the ready function will be called two times if both elements will fire their onload function

Navigating to Blacklisted URL's and Canceling Them

I need to write a Firefox extension that creates a blacklist and whitelist of URL's, and checks to make sure the user wants to navigate to them whenever the user attempts to do so. I'm doing this using a main script and a content script that I attach to every page (using PageMod); I attached a listener using jQuery to every link (with the tag "a") which executes a function using window.onbeforeunload. I have two questions:
How would I prompt/ask the user if they actually did want to go to the site?
How would I stop the browser from navigating to the site if the user decided not to?
Right now my code passes messages between the two scripts in order to accomplish my goal; as far as I can tell, I can only use "document" in the content script, and save the blacklist/whitelist in the main script. I'm using simple-storage to save my lists, and the port module to pass messages between the scripts.
For question 1, I've attempted using confirm(message) to get a positive/negative response from the user, but the popup either doesn't show up or shows up for a split second then gets automatically answered with a negative response. When I look in my console's error messages, I see a "prompt aborted by user" error.
For question 2, I've already tried using event.preventDefault() by passing the click event to the function (this worked, I think). Is there a better way to do this? I've seen people using window.location = "", et cetera to do this.
Anyways, the code is below:
MAIN.JS
var ss = require("sdk/simple-storage");
exports.main = function() {
if (!ss.storage.blacklist) {
ss.storage.blacklist = [];}
if (!ss.storage.whitelist) {
ss.storage.whitelist = [];}
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "*",
contentScriptFile: [data.url("jquery-1.10.2.min.js"),data.url("secChk.js")],
onAttach: function(worker) {
function whiteCNTD(str) {
for (var index = 0; index < ss.storage.whitelist.length; index++) {
if (ss.storage.whitelist[index] == str) {
return index;
}
}
return -1;
}
function blackCNTD(str) {
for (var index = 0; index < ss.storage.blacklist.length; index++) {
if (ss.storage.blacklist[index] == str) {
return index;
}
}
return -1;
}
function checkLists(URL) {
if (whiteCNTD(URL) == -1) {
if (blackCNTD(URL) != -1) {
var bool = false;
worker.port.emit("navq", "Do you want to go to this link and add it to the whitelist?");
worker.port.on("yes", function() {
bool = true;
});
worker.port.on("no", function() {
bool = false;
});
if (bool == true) {
ss.storage.blacklist.splice(index, 1);
ss.storage.whitelist.push(URL);
return true;
}
else {
return false;
}
}
else {
var bool = false;
worker.port.emit("safeq", "Is this a safe site?");
worker.port.on("yes", function() {
bool = true;
});
worker.port.on("no", function() {
bool = false;
});
if (bool == true) {
ss.storage.whitelist.push(URL);
return true;
}
else {
ss.storage.blacklist.push(URL);
return false;
}
}
}
return true;
}
worker.port.on("newURL", function(URL) {
var s = "";
s = URL;
if (checkLists(s)) {
worker.port.emit("good", s);
} else if (!checkLists(s)) {
worker.port.emit("bad", s);
}
});
}
});
}
SECCHK.JS
//Check if the site is a bad site whenever a link is clicked
$("a").click(function(event) {
window.onbeforeunload = function() {
self.port.on("navq", function(message) {
var r = confirm("Do you want to go to this link and add it to the whitelist?");
if (r == true) {
self.port.emit("yes", message);
} else if (r == false) {
self.port.emit("no", message);
}
});
self.port.on("safeq", function(message) {
var r = confirm("Is this a safe site?");
if (r == true) {
self.port.emit("yes", temp);
} else if (r == false) {
self.port.emit("no", temp);
}
});
link = document.activeElement.href;
self.port.emit("newURL", link);
self.port.on("good", function(message) {
return true;
});
self.port.on("bad", function(message) {
return false;
});
}
});

Categories

Resources