JavaScript integer storing as undefined for some reason - javascript

basically I have a number stored within my javascript structure, something like the following:
MyProgram.data.main.padding;
console.log(MyProgram.data.main.padding); // will output the number, something like 34.
However, I need to store that number in a struct I have set up in
MyProgram.data.tests.main.padding; // this is a struct " {'width':0, 'padding':0, 'acceptable' //etc...}
The problem is when I do this:
MyProgram.data.tests.main.padding = MyProgram.data.main.padding;
console.log(MyProgram.data.tests.main.padding); // shows undefined
any ideas why I can't store the number?
I really appreciate any help...
Can someone load this example on jsfiddle please? I don't know how:
http://jsfiddle.net/hdnj52Lp/2/
RESULT OUTPUT ON MY LOCAL TEST: 0) acceptable: true fontSize undefined padding: undefined
function MyProgram() {
var mp = this;
this.main = {
'data' : {
'padding': 50,
'fontSize': 10,
'tests' : {
'padding':null,
'fontSize':null,
'results':new Array()
}
},
'test' : function () {
console.log('running');
var testResult = {'acceptable':false,
'fontSize':0,
'padding':0}
//after some testing:
var newComputedPadding = 100;
var newComputedFontSize = 32;
var acceptable = true;
testResult.acceptable = acceptable;
testResult.fontSize = newComputedFontSize;
testResult.padding = newComputedPadding;
mp.main.data.tests.results.push(testResult);
mp.main.outputResults();
},
'outputResults' : function () {
for(var i = 0; i < mp.main.data.tests.results.length; i++) {
console.log( i + ') acceptable: ' + mp.main.data.tests.results[i].acceptable + ' fontSize ' + mp.main.data.tests.results.fontSize + ' paddingSides: ' + mp.main.data.tests.results.padding);
}
}
}
}
var Load;
if (window.attachEvent) {
Load =function ( elem, event, handler ) {
elem.attachEvent( 'on'+event, function load() {
handler();
elem.detachEvent( 'on'+event, load );
});
};
} else {
Load =function ( elem, event, handler ) {
elem.addEventListener( event, function load() {
handler();
elem.removeEventListener( event, load, false );
}, false);
};
}
Load(window, 'load', function() {
var MP = new MyProgram();
MP.main.test();
});

You are simply printing
mp.main.data.tests.results.fontSize
instead of
mp.main.data.tests.results[i].fontSize
The code is correct for acceptable but you forgot the [i] part for fontSize and padding.

Related

async and set timeout

I am having some problem using the settimeout() in my function. I am new to async. No matter how much I try I just can't make the timeout work. My code works perfect so that is not the problem. I need the request to execute every 10 seconds. Thanks for the help.
function getContent() {
function getPelicula(pelicula, donePelicula) {
var peli = pelicula.title;
//request id
request({
url: "http://api.themoviedb.org/3/search/movie?query=" + peli + "&api_key=3e2709c4c051b07326f1080b90e283b4&language=en=ES&page=1&include_adult=false",
method: "GET",
json: true,
}, function(error, res, body) {
if (error) {
console.error('Error getPelicula: ', error);
return;
}
var control = body.results.length;
if (control > 0) {
var year_base = pelicula.launch_year;
var id = body.results[0].id;
var year = body.results[0].release_date;
var d = new Date(year);
var year_solo = d.getFullYear();
if (year_base == year_solo) {
pelicula.id = id;
pelicula.year_pagina = year_solo;
}
} else {
pelicula.id = null;
pelicula.year_pagina = null;
}
donePelicula();
});
}
}
To do something in a loop, use setInterval.
UPD:
In general, there're two ways of executing some code in loop
1 setTimeout :
var someTimer = setTimeout(function sayHello(){
console.log("hello!");
someTimer = setTimeout(sayHello, 2000);
}, 2000);
Notice that someTimer variable is needed to stop the looping process if you need: clearTimeout(someTimer)
2 setInterval:
var someIntervalTimer = setInterval(function(){
console.log("I'm triggered by setInterval function!");
}, 2000);
Invoke clearInterval(someIntervalTimer) to stop the looping
Both functions are treated as properties of the global Window variable. By default, the following code works:
var window = this;
console.log("type of setTimeout: " + typeof window.setTimeout);
console.log("type of setInterval: " + typeof window.setInterval);
Try putting it in another function so:
domore(pelicula,donePelicula);
function domore(pelicula,donePelicula) {
// 1 second
var timeout = 1000;
for (var i = 1; i < pelicula.length; i++) {
createData(pelicula[i],donePelicula,timeout);
timeout = timeout + 800;
}
}
function createData(peli,donePelicula,timeout) {
setTimeout(function() { getData(peli,donePelicula); }, timeout);
}
function getData(peli,donePelicula) {
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://api.themoviedb.org/3/search/movie?query=" + peli + "&api_key=3e2709c4c051b07326f1080b90e283b4&language=en=ES&page=1&include_adult=false", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
domore(allText,donePelicula);
}
}
}
txtFile.send(null);
}

Convert script for working with multiple instances

Lets see this script, that it's a simple carrousel
$script = {
init: function(){
this.heros(3000);
},
heros: function (time) {
var t;
var $hero = $('.hero');
var $images = $('.hero > div');
$hero.data('current', 0);
var $bullets = $('<div>').addClass('bullets');
for ( var i = 0; i<$images.length; i++ ) {
var $item = $('<span>');
$item.on('click', function () {
clearTimeout(t);
play( $(this).index() );
});
if(i==0) { $item.addClass('active') }
$bullets.append( $item );
}
var play = function (current) {
if(current==undefined) {
current = $hero.data('current');
}
var nextMargin;
if ( (current+1) == $images.length ) {
nextMargin = 0 ;
$hero.data('current',0);
} else {
nextMargin = (current + 1 )*100;
$hero.data('current', (current + 1));
}
$images.eq(0).css('marginLeft', -nextMargin + '%');
$bullets.find('span').eq($hero.data('current')).addClass('active').siblings().removeClass('active');
clearTimeout(t);
t = setTimeout(play, time);
}
$hero.append($bullets);
t = setTimeout(play, time);
},
}
The thing is that it works great, but only if there's just one .hero element.. if there are multiple the bullets mix up and it doesn't respect the .length
I know that option one should be rewrite it again, but Does anyone of you sees a quick fix that would make it reusable?
A single fiddle: https://jsfiddle.net/6z8n5pnq/
A multiple fiddle: https://jsfiddle.net/6z8n5pnq/1/
-EDIT-
I tried:
Defining a previous function, that is called on init
preheros: function(time) {
var self = this;
$('.heros').each(function(){
self.heros($(this), time);
});
},
And editing The begining of heros:
heros: function ($hero, time) {
var t;
/*var $hero = $('.hero');*/
var $images = $hero.find('>div');
but no success...
any idea?
-EDIT-
GOD, it's $('.hero').each not $('.heros').each it was working!
The easiest way to do this is to isolate context for each .hero component by using $(selector).each function. Slightly corrected your fiddle https://jsfiddle.net/6z8n5pnq/2/
function apply($hero, time){
var t;
var $images = $hero.children('div');
//all your logic here...
}
$script = {
init: function () {
this.heros(3000);
},
heros: function (time) {
$('.hero').each(function(){
apply($(this), time);
});
},
}

Feature detection for parallax / background-position

Ok, so I've created my own parallaxing jQuery/JS script, but I just don't know how to target browsers that will support the following (needs the following):
Supports transition for background-position
The site (preview) I'm trying this at is:
My Test Site
How can I detect whether a browser will support this though?
Can I run media queries bases on window width?
Do I have to browser sniff?
I can't see anything on the WWW that gives me clues as to how I can feature-detect for this.
Any help would be greatly appreciated.
My JS code is here: (please feel free to use it if you like it)
var goTop = 0;
var thisGoTop = 0;
var thisHeight = 0;
var thisWinH = 0;
var bottomIntrusion = 0;
var thisMax = 0;
var bgPos = 0;
function parallax(){
goTop = $(window).scrollTop();
thisWinH = $(window).height();
$('div.para').each(function(){
thisGoTop = $(this).offset().top;
thisHeight = $(this).height();
thisMax = Math.floor(thisHeight * 0.3);
bottomIntrusion = (thisGoTop + (thisHeight / 2) - goTop) / thisWinH;
if (bottomIntrusion > 0) {
bgPos = 0 - (Math.floor(thisMax * bottomIntrusion));
$(this).css('background-position','center ' + bgPos + 'px');
}
});
}
parallax();
$(window).scroll(function(){
parallax();
});
Edit:
I've looked into the Modernizr library, and I haven't found anything that gives me clues about background-position transform support for CSS3. I'm getting real close to brower sniffing at this point, and I'd hate to go there.
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$( document ).ready( function() {
var Compatibility = function()
{
var context = this;
context.TestObject = function( id )
{
function CreateObject( id )
{
$('body').prepend('<div id="CompatibilityTestObject_' + id + '"></div>');
}
// Constructor
CreateObject( id );
return {
GetObject: function( id )
{
try
{
// Fetch with raw Javascript so if the javascript method does not exist it will throw an error
var fetchedDomElement = document.getElementById( "CompatibilityTestObject_" + id );
return fetchedDomElement;
}
catch( e )
{
// Failed to fetch DOM Element
return false;
}
},
DeleteObject: function( id )
{
try
{
$( "#CompatibilityTestObject_" + id ).remove();
return true;
}
catch( e )
{
// Failed to remove object
return false;
}
}
}
}
context.Factory = function()
{
return {
CreateTestObject: function( id )
{
var m_TestObject = new context.TestObject( id );
return m_TestObject.GetObject( id );
},
DeleteTestObject: function( id )
{
return context.DeleteObject( id );
}
}
}();
var CSS = function()
{
return {
BackgroundPosition: function()
{
var testObject = context.Factory.CreateTestObject( "BackgroundPosition" );
try
{
// My first try at testing for background positioning
testObject.style.backgroundPosition = "center";
return true;
}
catch( e )
{
// Implement the handling of this error
//alert( "Does not support backgroundPosition: " + e.message );
return false;
}
}
}
}();
return {
CheckCSS: CSS
}
}();
} );
</script>
Take a copy of the above script... place it in your code there, then call upon it like so:
if( Compatibility.CheckCSS.BackgroundPostion() )
{
// Compatible browser
}
else
{
// Not compatible
}

Accessing a jQuery Closure function outside

I have this code embedded in my file for managing session time out. This was referred from http://www.fairwaytech.com/2012/01/handling-session-timeout-gracefully/
I want to call SessionManager.extend() for all the ajax request
complete. So i can automatically refresh my session manager time.
This is what i tried
<script type="text/javascript">
$(document).ajaxSuccess(function (event, xhr, settings) {
if (xhr.status === 200) {
SessionManager().extend();
}
});
</script>
Getting an error that SessionManager object not found. How do we call this?
Below is the library code taken from that site
$(function () { // Wrap it all in jQuery documentReady because we use jQuery UI Dialog
// HtmlHelpers Module
// Call by using HtmlHelpers.getQueryStringValue("myname");
var HtmlHelpers = function () {
return {
// Based on http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript
getQueryStringValue: function (name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
};
} ();
// StringHelpers Module
// Call by using StringHelpers.padLeft("1", "000");
var StringHelpers = function () {
return {
// Pad string using padMask. string '1' with padMask '000' will produce '001'.
padLeft: function (string, padMask) {
string = '' + string;
return (padMask.substr(0, (padMask.length - string.length)) + string);
}
};
} ();
// SessionManager Module
var SessionManager = function () {
// NOTE: globalTimeoutPeriod is defined in _Layout.cshtml
var sessionTimeoutSeconds = HtmlHelpers.getQueryStringValue('smt') || (globalTimeoutPeriod),
countdownSeconds = HtmlHelpers.getQueryStringValue('smc') || 300,
secondsBeforePrompt = sessionTimeoutSeconds - countdownSeconds,
$dlg,
displayCountdownIntervalId,
promptToExtendSessionTimeoutId,
originalTitle = document.title,
count = countdownSeconds,
extendSessionUrl = '/Session/Extend',
expireSessionUrl = '/Session/Expire?returnUrl=' + location.pathname;
var endSession = function () {
$dlg.dialog('close');
location.href = expireSessionUrl;
};
var displayCountdown = function () {
var countdown = function () {
var cd = new Date(count * 1000),
minutes = cd.getUTCMinutes(),
seconds = cd.getUTCSeconds(),
minutesDisplay = minutes === 1 ? '1 minute ' : minutes === 0 ? '' : minutes + ' minutes ',
secondsDisplay = seconds === 1 ? '1 second' : seconds + ' seconds',
cdDisplay = minutesDisplay + secondsDisplay;
document.title = 'Expire in ' +
StringHelpers.padLeft(minutes, '00') + ':' +
StringHelpers.padLeft(seconds, '00');
$('#sm-countdown').html(cdDisplay);
if (count === 0) {
document.title = 'Session Expired';
endSession();
}
count--;
};
countdown();
displayCountdownIntervalId = window.setInterval(countdown, 1000);
};
var promptToExtendSession = function () {
$dlg = $('#sm-countdown-dialog')
.dialog({
title: 'Session Timeout Warning',
height: 250,
width: 350,
bgiframe: true,
modal: true,
buttons: {
'Continue': function () {
$(this).dialog('close');
refreshSession();
document.title = originalTitle;
},
'Log Out': function () {
endSession(false);
}
}
});
count = countdownSeconds;
displayCountdown();
};
var refreshSession = function () {
window.clearInterval(displayCountdownIntervalId);
var img = new Image(1, 1);
img.src = extendSessionUrl;
window.clearTimeout(promptToExtendSessionTimeoutId);
startSessionManager();
};
var startSessionManager = function () {
promptToExtendSessionTimeoutId =
window.setTimeout(promptToExtendSession, secondsBeforePrompt * 1000);
};
// Public Functions
return {
start: function () {
startSessionManager();
},
extend: function () {
refreshSession();
}
};
} ();
SessionManager.start();
});
Remove the var prefix from SessionManager.
Bit of info here about scope, http://msdn.microsoft.com/en-us/library/ie/bzt2dkta(v=vs.94).aspx

"$.______ is not a function" error. What is wrong?

I'm trying to add an image rotator to my site but for some reason firebug tells me the function I need to call to start the rotator isn't defined. My jQuery file is loading just fine and the image rotator script is loading so I'm not sure what is wrong. The site is heritage.newcoastmedia.com but I'll go ahead and post the script:
;(function($) {
$.fn.featureList = function(options) {
var tabs = $(this);
var output = $(options.output);
new jQuery.featureList(tabs, output, options);
return this;
};
$.featureList = function(tabs, output, options) {
function slide(nr) {
if (typeof nr == "undefined") {
nr = visible_item + 1;
nr = nr >= total_items ? 0 : nr;
}
tabs.removeClass('current').filter(":eq(" + nr + ")").addClass('current');
output.stop(true, true).filter(":visible").fadeOut();
output.filter(":eq(" + nr + ")").fadeIn(function() {
visible_item = nr;
});
}
var options = options || {};
var total_items = tabs.length;
var visible_item = options.start_item || 0;
options.pause_on_hover = options.pause_on_hover || true;
options.transition_interval = options.transition_interval || 5000;
output.hide().eq( visible_item ).show();
tabs.eq( visible_item ).addClass('current');
tabs.click(function() {
if ($(this).hasClass('current')) {
return false;
}
slide( tabs.index( this) );
});
if (options.transition_interval > 0) {
var timer = setInterval(function () {
slide();
}, options.transition_interval);
if (options.pause_on_hover) {
tabs.mouseenter(function() {
clearInterval( timer );
}).mouseleave(function() {
clearInterval( timer );
timer = setInterval(function () {
slide();
}, options.transition_interval);
});
}
}
};
});
And here is the script to start the image rotator:
<script language="javascript">
$(document).ready(function() {
$.featureList(
$("#tabs li a"),
$("#output li"), {
start_item : 1
}
);
});
</script>
Your code creates an anonymous function, but doesn't call it.
You need to call the function by adding (jQuery) at the end.
You cannot do $.featureList(
See Chrome error:
The plugin needs to applied to an object
You've just slightly missed out on the right syntax for creating a plugin. What you really want is:
(function($) {
$.fn.featureList = function() { // etc; }
$.featureList = function() { // yet more etc; }
})(jQuery);

Categories

Resources