I want to access var w value from other function. Is it possible.
<script type="text/javascript">
var first = {
myFirst: function(){
var w= 90;
var q=12;
}}
var second= {
mySecond: function(){
first.myFirst.w
}}
</script>
In that way you cannot access w because it's defined in the local scope of myFirst. You can do something like:
var first = {
myFirst: function(){
first.myFirst.w = 90;
var q=12;
}
};
var second= {
mySecond: function(){
alert(first.myFirst.w);
}
};
first.myFirst();
second.mySecond(); //alerts 90
In that way w will be added as property of the function myFirst, if you want to add it as property of first, use:
var first = {
myFirst: function(){
this.w = 90;
var q=12;
}
};
var second= {
mySecond: function(){
alert(first.w);
}
};
first.myFirst();
second.mySecond(); //alerts 90
No, that's not possible, because the scope of w is within the function. Once the function has been called w no longer exists.
Also, technically you would need to call first.myFirst().w;
To get that to work you could do this instead:
var first = {
myFirst: function(){
var w= 90;
var q=12;
return { w : w };
}
}
first.myFirst().w // now works.
Related
I have created a Constructor class / function that has 4 methods and a 5 attributes. The problem is when i create a new instance of the constructor it doesn't inherit the first attribute (this.el = element) which is 'affiliateSection' on the new instance called: animation1. Thanks in advance..
// main class
function AnimateImages(el, time, effect, setTime, h){
this.el = element; // this is not inheriting from 'animate1'
this.time = time;
this.effect = effect;
this.setTime = setTime;
this.h = height;
this.delayAnimate = function() {
this.element.delay(time)
.queue(function(next) {
$(this).addClass(effect);
next();
});
};
// function for multi animations
var multiAnimations = function() {
var i = 0;
this.element.each(function (key, value) {
i = i + setTime;
var tthis = this;
delayAnimate($(this), i, tthis.effect);
});
};
// load on window height
var onWindowAnimate = function () {
if ($(this).scrollTop() > this.height) {
// call multi animations function
var tthis = this;
multiAnimations(this.element, tthis.setTime, tthis.effect);
}
};
// hide function
var hideAnimatedEl = function (){
this.element.each(function(){
$(this).css("visibility", "hidden");
});
};
} // End of AnimateImages
/*============================================================*/
var affiliateSection = $("#aff-img > li > img");
// new instance of AnimateImages
var animation1 = new AnimateImages(affiliateSection, 200, 'subtlefadeIn',
300, 50);
$(window).scroll(function () {
setTimeout(function(){
animation1.onWindowAnimate();
}, 1000);
});
It looks like you have your member variable initializations backwards. Try this:
this.element = el; // this is not inheriting from 'animate1'
this.time = time;
this.effect = effect;
this.setTime = setTime;
this.height = h;
Your parameter name is wrong:
this.el = element;
element is not in the parameter list.
Since you are reffering to this.element inside your function, I am assuming that your first line should be
this.element = el;
I have written some jQuery functions, and recently realized I needed to reuse the code for another situation. I refactored the code to accept a selector as an arguement, so I can now use for case 1, and case 2. However, when I execute my functions in document.ready I get weird results.
$( document ).ready(function() {
imageCalc('.com-background > img');
setImageDims('.com-background > img', '#main-content');
imageCalc('.blog-entry-content iframe');
setImageDims('.blog-entry-content iframe', '#content');
});
It should be noted, these selectors do no show up on the same page. Also, when I only run one instance of imageCalc() and setImageDims() These functions work just fine. Here are the functions in question..
function imageCalc(selector) {
var obj=$(selector);
$imgWidth = obj.width();
$imgHeight = obj.height();
$imgAspectRatio = $imgHeight / $imgWidth;
// $(selector).css('margin-left', function( calcMargin ) { return parseInt($('.main-content').css('padding')) * -1 + "px"; }); fix for ie
obj.css('margin-left', '-10px' );
}
function setImageDims(selector, content_area) {
var container = $(content_area);
$(selector).css('height', function() { return $imgAspectRatio * container.width(); });
$(selector).css('width', function() { return container.width() + 20; });
}
In summary, all the code works just fine, when I only have each function called only ONCE in document.ready but I need to use this code for 2 scenarios, how can I do this?
Add a var in front of your $imgWidth, $imgHeight, and $imgAspectRatio variables. Without the var, they're being declared at global scope, and therefore accidentally getting shared across both calls to that function.
UPDATE: I just noticed that the $imgAspectRatio is being used by both functions. Perhaps you can make that the return value from the first function, so it can be passed into the second function.
To elaborate... something like this should theoretically work, although I'm not able to test it since I don't have the corresponding HTML:
function imageCalc(selector) {
var obj=$(selector);
var $imgWidth = obj.width();
var $imgHeight = obj.height();
var $imgAspectRatio = $imgHeight / $imgWidth;
// $(selector).css('margin-left', function( calcMargin ) { return parseInt($('.main-content').css('padding')) * -1 + "px"; }); fix for ie
obj.css('margin-left', '-10px' );
return $imgAspectRatio;
}
function setImageDims(selector, content_area, $imgAspectRatio) {
var container = $(content_area);
$(selector).css('height', function() { return $imgAspectRatio * container.width(); });
$(selector).css('width', function() { return container.width() + 20; });
}
$( document ).ready(function() {
var ratio1 = imageCalc('.com-background > img');
setImageDims('.com-background > img', '#main-content', ratio1);
var ratio2 = imageCalc('.blog-entry-content iframe');
setImageDims('.blog-entry-content iframe', '#content', ratio2);
});
This will require you to re-work your functionsas setImageDims depends on $imgAspectRatio to be available globally.
function imageCalc(selector) {
var obj=$(selector),
$imgWidth = obj.width(),
$imgHeight = obj.height(),
$imgAspectRatio = $imgHeight / $imgWidth;
// $(selector).css('margin-left', function( calcMargin ) { return parseInt($('.main-content').css('padding')) * -1 + "px"; }); fix for ie
obj.css('margin-left', '-10px' );
return $imgAspectRatio;
}
function setImageDims(selector, content_area) {
var container = $(content_area);
$(selector).css('height', function() { return imageCalc(selector) * container.width(); });
$(selector).css('width', function() { return container.width() + 20; });
}
h = function(){
x = function(){
alert("try");
}();
x;
};
I'm confused about this behavior: the inner function is immediately invoked, and it's ok. But why i must have an assignment? Why i can't write it anonymously?
I added a var and moved the internal execution down a line
h = function(){
var x = function(){
alert("try");
};
x();
};
then you can invoke h
h();
or you can invoke it directly with
h = function(){
var x = function(){
alert("try");
};
x();
}();
or you can twist it into the module pattern with
h = function(){
var x = function(){
alert("try");
};
return {
x:x
};
};
h().x();
Hope that helps
You can write it anonymously, of course:
(function(){
(function(){
alert("try");
})();
}) ();
In fact, your example is not working, since you forgot to invoke it in the last line:
} ();
See JSFiddle
I have this code:
var viewport = $(window),
viewport_height = viewport.height();
var _topPanel = jQuery.extend({
el: $('.js-lp_top'),
//
height: function() {
var self = this;
self.el.css('min-height', viewport_height);
},
scroll : function() {
var self = this;
var scrolled = viewport.scrollTop();
viewport.on('scroll', function() {
self.el.css({
'top': (49 - (scrolled / viewport_height) * 80) + '%'
});
});
}
});
var topPanel = new _topPanel.height().scroll();
And an jQuery error that Cannot read property 'css' of undefined. What i'm doing wrong? Thx for help.
Let's first examine this line of code.
var topPanel = new _topPanel.height().scroll();
The keyword new creates a new empty object. Inside the height function, the this keyword refers to this new object, which of course doesn't have an el property. self.el is undefined, hence the error message Cannot read property 'css' of undefined
There are two changes to make here:
Ensure your height and scroll functions returns this, to support function chaining
Don't include the new keyword when invoking the height function
Here's the modified code:
var _topPanel = jQuery.extend({
el: $('.js-lp_top'),
//
height: function () {
var self = this;
self.el.css('min-height', viewport_height);
return self;
},
scroll: function () {
var self = this;
var scrolled = viewport.scrollTop();
viewport.on('scroll', function () {
self.el.css({
'top': (49 - (scrolled / viewport_height) * 80) + '%'
});
});
return self;
}
});
var topPanel = _topPanel.height().scroll();
Probably a really easy question
I've been searching, but I could not find what window.h means? Only some articles about C++ but not about javascript.
view: {
fc: "",
init: function() {
var iframe = $("iframe")[0];
var focused = true;
var unfocusedTimeStart = null;
var unfocusedTime = null;
var loaded = false;
var prevent_bust = 0;
var done = false;
window.onbeforeunload = function() {
prevent_bust++;
};
setInterval(function() {
if (prevent_bust > 0 && !done) {
prevent_bust -= 2;
}
}, 1);
var mySwfStore = new SwfStore({
namespace: "BTCClicks",
swf_url: "/js/storage.swf",
onready: function() {
var fcookie = mySwfStore.get("fcookie");
var randomstring = md5(randomstring);
if (fcookie == null) {
mySwfStore.set("fcookie", randomstring);
}
fcookie = mySwfStore.get("fcookie");
if (fcookie != null) {
BTCClicks.view.fc = fcookie;
}
},
onerror: function() {}
});
$("#viewFrame").load(function() {
if (!loaded) {
$.post("/ajax/vrequest", {
ad: window.h,
fc: BTCClicks.view.fc
}).done(function() {
startTimer();
});
loaded = true;
}
});
Could someone explain what that means?
If refers to a variable named h in the global (window) scope
Whenever you make a global variable in JavaScript you can either refer to it by name or window.[variableName]
In this case you can either do
ad: window.h
or
ad: h
As long as there isn't another local variable named h