When the window loads, the console is returning indexIn.But when I run the bottom function, it returns NaN.
const recentItem = document.querySelector('.recent-item');
var indexIn;
window.onload = function() {
var indexIn = JSON.parse(localStorage.getItem("indexInStore"));
var indexOut = JSON.parse(localStorage.getItem("indexOutStore"));
var indexIn = Number(indexIn);
console.log(indexIn);
}
var indexIn = indexIn;
recentItem.addEventListener('click', function() {
console.log(indexIn);
});
Can you try:
const recentItem = document.querySelector('.recent-item');
var indexIn;
window.onload = function() {
indexIn = Number(JSON.parse(localStorage.getItem("indexInStore")));
var indexOut = JSON.parse(localStorage.getItem("indexOutStore"));
console.log(indexIn);
}
recentItem.addEventListener('click', function() {
console.log(indexIn);
});
You have indexIndefined globally then your are "redefining" it and setting in inside an "onload" function. Not good coding.
Related
Currently I am using protractor and using page object, so there is a file that I get the value of an element in a variable, but I need to call this value in another file.
vehiclePage.js
/*jshint esversion: 6 */
var basePage = require('./basePage.js');
var homePage = require('./homePage.js');
var VehiclePage = function() {
this.storeVehicleData = function() {
this.pessengersRuntValue = element(by.id('preview_ocupantes_runt')).getText();
};
};
VehiclePage.prototype = basePage; // extend basePage...
module.exports = new VehiclePage();
Now I need to use the value of the above variables in another file
checkoutPage.js
/*jshint esversion: 6 */
var basePage = require('./basePage.js');
var homePage = require('./homePage.js');
var CheckoutPage = function() {
this.getRuntValue = element(by.css('.mb10'));
this.compareValues = function() {
expect(this.getRuntValue.getText()).toContain(this.pessengersRuntValue);
};
};
CheckoutPage.prototype = basePage; // extend basePage...
module.exports = new CheckoutPage();
How can I make it work?
If you are following Page Object Design Pattern, I would say that the test should not be on the page object. I will write something like this.
VehiclePage.js
var VehiclePage = function(){
// if this is a browser testing something like this
browser.get('/vehicle');
};
VehiclePage.prototype = Object.create({}, {
runt: {
get: function(){
return element(by.id('preview_ocupantes_runt'));
}
}
});
module.export = VehiclePage;
CheckOutPage.js
var CheckOutPage = function(){
// if this is a browser testing something like this
browser.get('/checkout');
};
CheckOutPage.prototype = Object.create({}, {
runt: {
get: function(){
return element(by.css('.mb10'));
}
}
});
module.export = CheckOutPage;
TheTest.js
var VehiclePage = require('VehiclePage');
var CheckOutPage = require('CheckOutPage');
describe('testing something', () => {
var vehicle = new VehiclePage();
var checkout = new CheckOutPage();
it('should contain', () => {
expect(checkout.runt.getText()).toContains(vehicle.runt.getText());
});
});
One way to do this would be to pass a state object to both pages.
var VehiclePage = require('./vehiclePage.js');
var CheckoutPage = require('./checkoutPage.js');
class StateStorage {
constructor(){
this.savedVariable = null;
}
}
var state = new StateStorage();
var vehiclePage = new VehiclePage(state);
var checkoutPage = new CheckoutPage(state);
Then you can manipulate and access the state from both new pages.
I am trying to call the method getTitulo, getDuracion and getLink inside the cancion.js file but when i call the function it returns the following error: "listaCanciones_Lcl[i].getTitulo is not a function". I have searched in different websites but i didnt got lucky with finding an answer. Hopefully someone here can give me some help, i will gladly appreciate it!
//Logic.js file
var listaCanciones = [],
ejecuTitulo = '',
ejecuDuracion = '',
ejecuLink = '';
var btnGenerarLista = document.getElementById("addList").addEventListener("click", agregarCanc);
var btnAgregarLista = document.getElementById("gnrList").addEventListener("click", llenarTabla);
function agregarCanc (){
var nameSong = document.querySelector('#nameSong').value;
var duraSong = document.querySelector('#duraSong').value;
var linkSong = document.querySelector('#linkSong').value;
var objCancion = new Cancion(nameSong, duraSong, linkSong);
listaCanciones.push(objCancion);
var listaCancionesJson = JSON.stringify(listaCanciones);
localStorage.setItem('json_canciones', listaCancionesJson);
}
function llenarTabla (titulo){
var celdaTitulo = document.querySelector('#tituloList'),
celdaDuracion = document.querySelector('#duracionList'),
celdaLink = document.querySelector('#linkList'),
listaCanciones_Lcl = JSON.parse(localStorage.getItem('json_canciones'));
for(var i=0; i<listaCanciones_Lcl.length;i++){
// Acceder a lista canciones
I am getting an error in this line, where is says "getTitulo" is not a function but i dont really know why?
var nodoTextoTitulo = document.createTextNode(listaCanciones_Lcl[i].getTitulo()),
nodoTextoDuracion = document.createTextNode(listaCanciones_Lcl[i].getDuracion()),
nodoTextoLink = document.createTextNode(listaCanciones_Lcl[i].getLink());
// Create td
var elementoTdTitulo = document.createElement('td'),
elementoTdDuracion = document.createElement('td'),
elementoTdLink = document.createElement('td');
// Celda Id Append Child
elementoTdTitulo.appendChild(nodoTextoTitulo);
elementoTdDuracion.appendChild(nodoTextoDuracion);
elementoTdLink.appendChild(nodoTextoLink);
// Fila Append Child
celdaTitulo.appendChild(elementoTdTitulo);
celdaDuracion.appendChild(elementoTdDuracion);
celdaLink.appendChild(elementoTdLink);
}
}
//Cancion.js File
var Cancion = function(pTitulo, pDuracion, pLink){
var id = 0;
var titulo = pTitulo;
var duracion = pDuracion;
var link = pLink;
this.getId = function (){
return id;
};
this.setTitulo = function (pTitulo){
titulo = pTitulo;
};
this.getTitulo = function(){
return titulo;
};
this.setDuracion = function(pDuracion){
duracion = pDuracion;
};
this.getDuracion = function(){
return duracion;
};
this.setLink = function (pLink){
link = pLink;
};
this.getLink = function(){
return link;
};
};
First, make sure you are loading the Cancion.js file before the others in your HTML. Your problem is that when you parse the JSON back out of local storage, Cancion is not a known object, so getTitulo is undefined. You'll have to do listaCanciones_Lcl[i].titulo; instead.
And another change you'll need is to loosen the scope of your variables. The reason you need this.x = pX is because before JSON.stringify(new Cancion(1, 2, 3)) just returned "{}". With this code it returns "{"id":0,"titulo":1,"duracion":2,"link":3}", which I think is what you were after.
function Cancion(pTitulo, pDuracion, pLink){
this.id = 0;
this.titulo = pTitulo;
this.duracion = pDuracion;
this.link = pLink;
this.getId = function (){
return this.id;
};
this.setTitulo = function (pTitulo){
this.titulo = pTitulo;
};
this.getTitulo = function(){
return this.titulo;
};
this.setDuracion = function(pDuracion){
this.duracion = pDuracion;
};
this.getDuracion = function(){
return this.duracion;
};
this.setLink = function (pLink){
this.link = pLink;
};
this.getLink = function(){
return this.link;
};
};
var objWithFunction = {
name: 'Object with Function',
getName: function() { return this.name }
};
undefined
objWithFunction.getName() // --> "Object with Function"
var string = JSON.stringify(objWithFunction)
string // -=> "{"name":"Object with Function"}"
JSON is for data only..
Better you create a model, and fill it with data.. but this model has to exist in your application.. or you load the model parallel to your data..
function SomeThing() {};
SomeThing.prototype.getName = function() { return this.name };
var Thing1 = new SomeThing(JSON.parse("{name:'ThingOne'}"));
Thing1.getName(); // ThingOne
I am loading in a js file to build a form (I know this isn't standard; this is just for my learning). The contents of that file look like this:
window.captor = (function () {
function Captor () {
}
var captor = {
create: function () {
return new Captor();
}
};
Captor.prototype.build = function (json) {
//CREATE BACKDROP WITH CLOSE FUNCTION
var interstitial = this.backdrop();
//CREATE DIV CONTAINER
var container = this.container();
//CREATE TITLE
var title = this.setTitle();
//CREATE CALL TO ACTION
var cta = this.callToAction();
//CREATE FORM WITH INPUTS
var form = this.capture(json);
interstitial.appendChild(container);
container.appendChild(title);
container.appendChild(cta);
container.appendChild(form);
document.body.parentNode.appendChild(interstitial);
};
Captor.prototype.backdrop = function(){
var b = document.createElement("div");
b.setAttribute('style',"position:fixed;width:100%;height:100%;background: rgba(0,0,0,.6);z-index: 100;");
return b;
};
Captor.prototype.container = function(){
var c = document.createElement("div");
c.setAttribute('style',"position:relative;background:#dedede;min-height:100px;width: 480px;margin: auto;top: 45%;-webkit-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px;");
return c;
};
Captor.prototype.setTitle = function(){
var t = document.createElement("h1");
var inside = document.createTextNode("Join Our Newsletter");
t.appendChild(inside);
return t;
};
Captor.prototype.callToAction = function(){
var cta = document.createElement("p");
var inside = document.createTextNode("Would you like to find out more about stuff? Join our newsletter!");
cta.appendChild(inside);
return cta;
};
Captor.prototype.capture = function(json){
var f = document.createElement("form");
var hidden = document.createElement("input");
hidden.setAttribute('type',"hidden");
f.appendChild(hidden);
return f;
};
return captor;
}());
Then after including that file, I call:
var n = captor.create();
n.build(window.builder.getj);
Where window.builder.getj returns a json object (I haven't done anything with that obj, just yet).
So far, the form doesn't build. I'm not sure if anything is getting called. When I look at the console, nothing is output. If I call var c = captor.create(); it returns undefined. If I run c = captor.create(); it returns Captor {build: function, backdrop: function, container: function, setTitle: function, callToAction: function…}.
I feel like I must be missing something, but for the life of me I can't see what it is. How do I get this form to render in the correct way?
I have this function for coping values from window to window that is working one way, but not another...
Working script:
$(document).ready(function(e) {
$('#clickit').live({
click: function() {
window.opener.document.forms['orderForm']['service'].value = document.forms['GroundRates']['service'].value;
window.opener.document.forms['orderForm']['rate'].value = document.forms['GroundRates']['rate'].value;
self.close();
return false;
}
});
});
Now I on this other script, what did I do wrong? I'm pulling my hair out here.
Not working:
$(document).ready(function(e) {
$('#clickit').live({
click: function() {
var thisservice = document.forms['GroundRates']['service'].value;
var thisrate = document.forms['GroundRates']['rate'].value;
var thatservice = window.opener.document.forms['orderForm']['service'].value;
var thatrate = window.opener.document.forms['orderForm']['rate'].value;
$(thatrate) = $(thisrate);
$(thatservice) = $(thisservice);
self.close();
return false;
}
});
});
I've also tried..
$(thatrate).val() = $(thisrate).val();
$(thatservice).val() = $(thisservice).val();
And..
thatrate = thisrate;
thatservice = thisservice;
But this works:
var service = document.forms['GroundRates']['service'].value;
var rate = document.forms['GroundRates']['rate'].value;
window.opener.document.forms['orderForm']['service'].value = service;
window.opener.document.forms['orderForm']['rate'].value = rate;
Am I not assigning the var correctly for the window.opener?
You're misusing .val()
$(thatrate).val($(thisrate).val());
$(thatservice).val($(thisservice).val());
The new value goes inside the parentheses.
var thisservice = document.forms['GroundRates']['service'];
var thisrate = document.forms['GroundRates']['rate'];
var thatservice = window.opener.document.forms['orderForm']['service'];
var thatrate = window.opener.document.forms['orderForm']['rate'];
thatrate.value = thatservice.value;
thatservice.value = thisservice.value;
or if you want to wrap the DOM objects with a jQuery object.
var thisservice = document.forms['GroundRates']['service'];
var thisrate = document.forms['GroundRates']['rate'];
var thatservice = window.opener.document.forms['orderForm']['service'];
var thatrate = window.opener.document.forms['orderForm']['rate'];
$(thatrate).val( $(thatservice).val() );
$(thatservice).val( $(thisservice).val() );
try:
var thisservice = document.forms['GroundRates']['service'];
var thisrate = document.forms['GroundRates']['rate'];
var thatservice = window.opener.document.forms['orderForm']['service'];
var thatrate = window.opener.document.forms['orderForm']['rate'];
thatrate.val(thisrate.val());
thatservice.val(thisservice.val());
Your console will tell you: ReferenceError: Invalid left-hand side in assignment
$(thatrate) = $(thisrate);
$(thatservice) = $(thisservice);
You should do it like this:
var thisservice = document.forms['GroundRates']['service'];
var thisrate = document.forms['GroundRates']['rate'];
var thatservice = window.opener.document.forms['orderForm']['service'];
var thatrate = window.opener.document.forms['orderForm']['rate'];
thatrate.value = thisrate.value
thatservice.value = thisservice.value;
Hello I have code which replaces document.write, makes a buffer and than pushes buffer into the document:
var lazyLoad = (function () {
var counter = 0
var buffer = new Array()
function work(options){
window.d = document
var tmp_buffer
d.write = d.writeln = function(s){ tmp_buffer += s}
d.open = d.close = function(){}
s = d.createElement('script')
s.setAttribute('type','text/javascript')
s.setAttribute('src',options.url)
d.getElementById(options.block).appendChild(s)
s.onload = function () {
buffer[counter] = tmp_buffer
console.log(buffer[1])
window.setTimeout(function() {
d.getElementById(options.block).innerHTML += buffer[counter]
}, 0)
counter++
}
}
return {
init: function (options) {
var CONFIG = {
url: '',
block: ''
}
$.extend(CONFIG, options)
random = $('#'+CONFIG.block).attr('rel')
id = $('#'+CONFIG.block).attr('id').replace(random,'')
id = id.replace('DIV','')
size = id.split('X')
ele_width = size[0] || CONFIG.width
ele_height = size[1] || CONFIG.height
$('#'+CONFIG.block).css({
'width':ele_width+'px',
'height':ele_height+'px'
})
$(window).load(function(){
if(options.adfox) {
random = $('#'+CONFIG.block).attr('id')
AdFox_getCodeScript(1, random, CONFIG.url)
}else{
work(options)
}
})
}
}
})();
If I init it once:
lazyLoad.init({
'http://test.com/test.js',
div1
})
But if I call it again with other parameters:
lazyLoad.init({
'http://test2.com/test.js',
div2
})
First init wont work. buffer will be empty. Where is my mistake?
I think that
$(window).load(function(){
will overwrite the event handler. Try using:
$(function(){
});
instead. I think it'll add an array of event handlers. I could be wrong though. Please let me know how it turns out.
Also, it doesn't look like you're defining "s" in the local scope. If you don't put "var" in front of a variable when you define it, it'll get created in the global scope.