javascript keeping count on how many times a picture is deleted - javascript

I never used javascript in this way, but I would like to keep track of how many times a delete button is pressed. When the page originally loads I want to set the "value" to 0 and as they press delete keep track. Here is what I have is what obviously does not work, I didnt want to go the route of making a hidden variable and keep track that way. Thanks for any help.
Script
var deletePictureCount;
function MenuAction() {
}
MenuAction.prototype = {
GetDeletePictureCount: function () {
if (deletePictureCount == null || deletePictureCount < 0) { return 0; }
return deletePictureCount;
},
SetDeletePictureCount: function () {
deletePictureCount++;
}
};
usage on delete
var incement = new MenuAction().SetDeletePictureCount();
usage when trying to get value back
var deletedPiccount = new MenuAction().GetDeletePictureCount();

Looks a little odd to me - you aren't setting an initial value to the variable, and you are creating two instances of an object to get/set the value? And you are setting a return value to increment but aren't returning a value in that function.
Why not just use deletePictureCount++ and be done with it?

Let's take a look at your script:
var deletePictureCount; - Better set it's initial value if you gon'na use "set" before "get" before ;
if (deletePictureCount == null || deletePictureCount < 0) { return 0; } - this term is needless: I didn't see how exactly your deletePictureCount can get a negative value through your script.
Use if( deletePictureCount ) return deletePictureCount; instead.
It should look like
var deletePictureCount = 0;
function MenuAction() {
}
MenuAction.prototype = {
GetDeletePictureCount: function () {
if ( deletePictureCount ) return deletePictureCount; //if deletePictureCount is not null or 0 - return it's value;
return 0; // else return 0;
},
SetDeletePictureCount: function () {
deletePictureCount++;
}
};

You need to initialize the deletePictureCount to 0 like here,
http://jsbin.com/axeyiq/2/edit#javascript,html

Related

Tiles dont turn right

I am making a website, http://phaidonasgialis.xyz. I want to make the tiles to turn and every other tile back. Until now it works except one small bug, the tile that you pressed does not turn back until you click second time.Any help would be thankful.
Here is the code:
$(document).ready(function() {
var previous = [];
$('.flip-card').each(function(i, obj) {
$(this).click(function() {
if ($(this).find('.flip-card-inner').hasClass('flip-card-transform')) {
$(this).find('.flip-card-inner').removeClass('flip-card-transform');
} else {
$(this).find('.flip-card-inner').addClass('flip-card-transform');
previous.push(this);
if (previous.length >= 2 && previous[previous.length - 2] != previous[previous.length - 1]) {
for (var i = 0; i < previous.length; i++) {
if ($(this).find('.flip-card-inner').hasClass('flip-card-transform')) {
$(previous[i - 1]).find('.flip-card-inner').removeClass('flip-card-transform');
console.log("2")
} else {
$(this).find('.flip-card-inner').addClass('flip-card-transform');
console.log("3")
}
}
}
}
});
});
If I understand your question correctly, you would like a card to flip back automatically after a certain period of time? If so then you just should set a Timeout and remove the class flip-card-transform from .flip-card-inner.
Aside note: you should definitely optimize your code by using a variable instead of doing $(this).find('.flip-card-inner')– converting this to jQuery object and searching trough its children every time when you need your flip-card-inner. Also instead of $('.flip-card').each(...) you could directly use $('.flip-card').click(...). And also as Harun Yilmaz suggested in his comment you don't need previous as an array...
So something like this should work:
$(document).ready(function () {
var previous
var timeout
$('.flip-card').click(function () {
var cardInner = $(this).find('.flip-card-inner')
if (cardInner.hasClass('flip-card-transform')) {
cardInner.removeClass('flip-card-transform')
clearTimeout(timeout)
} else {
cardInner.addClass('flip-card-transform')
// Set a Timeout
timeout = setTimeout(function () {
cardInner.removeClass('flip-card-transform')
}, 2000) // set whatever time sutable for you
// Also as Harun Yilmaz suggested in his comment you don't need previous as an array
if (previous && previous.hasClass('flip-card-transform')) {
previous.removeClass('flip-card-transform')
}
previous = cardInner
}
})
})

HTML Array script not working (in_Array not defined)

TL;DR Need help on making this script work
Hi, I've been trying to get this script working with an array structure but it doesn't work and I keep getting the error in_Array not defined. If possible can anyone point out the mistakes I am making even if it minimal. Thanks for your time -Simon
<script>
$traffictick = Array("OFF","ON","OFF");
function tick() {
if (in_Array("ON", $traffictick[1])) {
yellowon();
console.log("Yellow");
$traffictick = Array("OFF,OFF,ON;");
} else if (in_Array("ON", $traffictick[2])) {
redon();
console.log("Red");
$traffictick = Array("OFF,ON,ON;");
} else if (in_Array("ON", $traffictick[2])) {
yellowon();
console.log("Red & Yellow");
$traffictick = Array("ON,OFF,OFF;");
} else if (in_Array("ON", $traffictick[1] & $trafficktick[2])) {
greenon();
console.log("Green");
$traffictick = Array("OFF,ON,OFF;");
}
}
</script>
there is no in_array function in javascript, you have to check manually that your value exist in array or not,
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
Use this function instead of in_array and also you are passing value as a second parameter, you must pass an array.

Background function javascript

I work with javascript. Let's suppose I have the following function in my app:
function verify(cats) {
if ( cats > 20 ) {
// do something
}
}
Supposing i have a button to add cats, I may use that function after every cat adding.
However, i don't like this method.
I want that this function be in the background and is executed automatically when the condition states true
Is there some way to do so ?
Use a setter, that runs on every assignment. Before:
var obj = {};
obj.cats = 10;
obj.cats += 30;
verify(obj.cats); // we don't want to call this each time.
After:
var obj = {
_cats : 0, // private
get cats() { return this._cats; },
set cats(num) {
verify(num); // any verification here
this._cats = num;
}
};
Later, you can do:
obj.cats += 10; // will run verification
obj.cats = 15; // same
Alternatively, you can use a proxy, but those aren't really widely supported by JS engines yet.
How about setInterval()
$(function() {
setInterval(
function verify(cats) {
if ( cats > 20 ) {
// do something
}
}
, 10);
})

How do I use an array instead of the variables in this repetitive function?

So, I have this little code in my js file:
window.onload = function Equal() {
var a = 'b1'
var b = 'box1'
var bookstorname = localStorage.getItem(a)
if (bookstorname == 1) {
document.getElementById(b).setAttribute('checked','checked');
}
if (bookstorname == 0) {
document.getElementById(b).removeAttribute('checked','checked');
}
var a = 'b2'
var b = 'box2'
var bookstorname = localStorage.getItem(a)
if (bookstorname == 1) {
document.getElementById(b).setAttribute('checked','checked');
}
if (bookstorname == 0) {
document.getElementById(b).removeAttribute('checked','checked');
}
}
The function itself is not important (it equals checkboxvalues set in the localstorage), but I execute it 2 times. First time with var a & b set to 'b1' & 'box1'. Then I run the script again (same script), but with var a & b set to 'b2' & 'box2'. Now, this code works, but my question is if there is a shorter way to write this? I can imagine some sort of array with a loop, but I could not get it to work for some reason. The 2 variables are pairs, and I know this might be a dumb question, but I can't find the answer anywhere.
You can use a second function which will accept the local storage key and the checkbox id like
window.onload = function Equal() {
setCheckboxState('box1', 'b1');
setCheckboxState('box2', 'b2');
}
function setCheckboxState(id, key) {
document.getElementById(id).checked = 1 == localStorage.getItem(key);
}
You might separate common logic into another function
window.onload = function Equal() {
function extractFromStorage(a, b) {
var bookstorname = localStorage.getItem(a)
if (bookstorname == 1) {
document.getElementById(b).setAttribute('checked','checked');
}
if (bookstorname == 0) {
document.getElementById(b).removeAttribute('checked','checked');
}
}
extractFromStorage('b1', 'box1');
extractFromStorage('b2', 'box2');
}
function doTheStuff(a, b) {
var bookstorname = localStorage.getItem(a)
if (bookstorname == 1) {
document.getElementById(b).setAttribute('checked','checked');
}
if (bookstorname == 0) {
document.getElementById(b).removeAttribute('checked','checked');
}
}
window.onload = function Equal() {
doTheStuff('b1', 'box1');
doTheStuff('b2', 'box2');
}
?
This is how I would do it.
There are several problems with your code.
You do not check that the element you are stetting an attribute to
exists. You do not check if the localStorage item you get is
defined.
You pollute the global name space with the function name Equal.
That function should not be named with a capital as it is not a Object generator.
There is no need to use setAttribute and removeAttribute, in
fact removeAttribute makes no sense in this case as you can not
remove the checked attribute from the element. BTW why use setAttribute here and not for window.onload?
The checked attribute is either true or false, it does not use the
string "checked"
Binding the load event via the onload attribute is not safe as you may
block 3rd party code, or worse 3rd party code may block you.
There is no error checking. DOM pages are dynamic environments, pages
have adverts and content from many places that can interfer with your
code. Always code with this in mind. Check for possible errors and deal with them in a friendly way for the end user. In this case I used an alert, not friendly for a normal user but for you the coder.
My solution.
// add an event listener rather than replace the event listener
window.addEventListener(
"load", // for the load event
function(){
// the update function that is called for each item;
var update = function(item){
// the right hand side equates to true if the localstorage
// is equal to "1". LocalStorage allways returns a string or
// undefined if the key is not defined.
item.element.checked = localStorage[item.storageName] === "1";
}
// safe element getter
var getElement = function(eId){
var e = document.getElementById(eId); // try and get the element
if(e === null){ // does it exist?
throw "Missing element:"+eId; // no then we can not continue
// the program stops here unless
// you catch the error and deal with
// it gracefully.
}
return e; //ok return the element.
}
// Item creator. This creates a new item.
// sName is the local storage name
// eId id the element ID
var item = function(sName, eId){
return {
storageName: sName, // set the loaclStorage name
element:getElement(eId); // get the element and check its safe
};
}
// make it all safe
try{
// create an array of items.
var items = [
item("b1","box1"),
item("b2","box2")
];
// for each item update the element status
items.forEach(update);
}catch(e){
alert("Could not update page?");
}
}
);

How to store variables: Privileged method, static property

Instead of just saying:
var thing = timeConsumingMethod();
I have my variable hidden in a method like so:
function _thing() {
var thing = timeConsumingMethod() );
return thing;
}
It gets called a number of times. I'm concerned that I'm made things very inefficient. I assume it calls timeConsumingMethod every time (which is unneeded, it's always the same) I call "_thing()" to get my variable.
How do I manage these types of variables in simple efficient way? Is something like this a solution?:
function _thing() {
return _thing.thing
}
_thing.thing = timeConsumingMethod();
Basically, i want the protection of a function and to (ideally0 access my variable using _thing() or something similar, but I only want timeConsumingMethod to run once.
edit: tried this, doesn't work either:
function _thingy() {
var thing = timeConsumingMethod();
}
_thingy.test = function() {
return( _thingy.thing)
}
Why not just:
function SomethingTimeConsuming() { ... }
function LazyThing(sourceFunction) {
this.sourceFunction = sourceFunction;
this.value = null;
this.Value = function() {
if ( this.value == null) this.value = sourceFunction();
return this.value;
}
}
JSFiddle: http://jsfiddle.net/YSAjJ/
Output:
[14:20:20.079] Calling time-consuming function *(1 time)

Categories