Need to understand a portion of jquery code? - javascript

here i am posting a jquery code which is working but few lines are not clear to me .
js fiddle link.
full code
HTML:
<form method="post" action="WebForm1.aspx" id="ctl00">
<input type="submit" name="Button1" value="Fly DIV" id="Button1" class="toggleUPSContainer" />
</form>
CSS:
#UPSContainer{
position: absolute;
display: none;
background:red;
height:0;
width:0;
}
javascript:
$(document).ready(function () {
var $els = [];
var data = {
"UPSContainer": {
"height" : 100,
"width" : 100
},
"isAnimating" : false
};
$els.window = $(window);
$els.form = $('#ctl00');
$els.toggleUPSButtons = $('.toggleUPSContainer');
function addUPSOverlay(){
$els.form.append('<div id="UPSContainer"></div>');
$els.UPSContainer = $('#UPSContainer');
}
function getNewWindowCorner(){
data.windowWidth = parseInt($els.window.width());
data.windowHeight = parseInt($els.window.height());
if($els.UPSContainer.is(':hidden')){
$els.UPSContainer.css({
top: data.windowHeight + 'px',
left: data.windowWidth + 'px'
});
}else{
$els.UPSContainer.css({
left: ((data.windowWidth - data.UPSContainer.width) / 2) + 'px',
top: ((data.windowHeight - data.UPSContainer.height) / 2) + 'px'
});
}
}
function containerOpenComplete(){
// do what you want here when opening complete
}
function containerCloseComplete(){
// do what you want here when closing complete
}
function toggleUPSOverlay(e){
e.preventDefault();
if(!data.isAnimating){
if($els.UPSContainer.is(':hidden')){ // currently closed so open
$els.UPSContainer.show();
$els.UPSContainer.animate({
left: ((data.windowWidth - data.UPSContainer.width) / 2) + 'px',
top: ((data.windowHeight - data.UPSContainer.height) / 2) + 'px',
height: data.UPSContainer.height + 'px',
width: data.UPSContainer.width + 'px'
}, 200, function(){
containerOpenComplete();
});
}else{ // currently open so close
$els.UPSContainer.animate({
left: data.windowWidth + 'px',
top: data.windowHeight + 'px',
height: 0 + 'px',
width: 0 + 'px'
}, 200,
function () {
$els.UPSContainer.hide();
containerCloseComplete();
});
}
}
}
function attachEvents(){
$els.window.on('resize', getNewWindowCorner);
$els.toggleUPSButtons.on('click', toggleUPSOverlay);
}
function initialize(){
addUPSOverlay();
getNewWindowCorner();
attachEvents();
}
initialize();
});
this function's code is not clear
function getNewWindowCorner(){
data.windowWidth = parseInt($els.window.width());
data.windowHeight = parseInt($els.window.height());
}
just see windowWidth & windowHeight potion
var data = {
"UPSContainer": {
"height" : 100,
"width" : 100
},
"isAnimating" : false
};
data has been declared as object and it has property like height, width & isAnimating etc but how we can add two new property called windowWidth & windowHeight to data object ??
just seeing the below code it seems that we can add any property to any object with any name at runtime in javascript and here we are storing value to windowWidth & windowHeight property.
data.windowWidth = parseInt($els.window.width());
data.windowHeight = parseInt($els.window.height());
so just see my whole code and tell me from where these two property comes windowWidth & windowHeight ? thanks
EDIT 1
Need bit more help. what it is called in js var $els = [];? is it array or object? what is the difference between var $els = []; and var els = {}; ? if this is array var $els = []; then how one can push anything into array like this way $els.window = $(window); or $els.body = $('body');. please help me understand the usage with small sample. thanks

For normal ones you can add them on the fly. They don't have to be declared from the start with the object. If they are they'll only be overwritten.
So you could either add everything you want from the start...
var data = {
"UPSContainer": {
"height": 100,
"width": 100
},
"isAnimating": false
};
.. or create it as you go
var data = {};
data.UPSContainer = {};
data.UPSContainer.height = 100;
data.UPSContainer.width = 100;
data.isAnimating = false;
data.windowWidth = parseInt($els.window.width());
data.windowHeight = parseInt($els.window.height());

it seems that we can add any property to any object with any name at runtime in javascript
Yes. You can. You just assign the new values.
where these two property comes windowWidth & windowHeight
From the code you are asking about. The assignment creates those properties.

In ECMAscript3 and ECMAScript5 , any property can be added to any object,
either by dot assignment, or through an array type notation.
data.windowWidth = parseInt($els.window.width());
or
data['windowWidth'] = parseInt($els.window.width());
create 'windowWidth' property for the data object.
In ECMA5 , this behaviour can be altered by following function:
Object.preventExtensions( obj )
and you can use Object.isExtensible( obj ) to check the current behaviour of that object.
If you try adding property to such an object for which extensions have been prevented, you would get an error in strict mode.
For your second question, in javascript array is also an object having properties , date is also an object , hence you can add properties to the array.

Related

Set css properties with a json

i've follow the w3c description for setting up the css properties of an element with javascript, but i cant figure how to do it with a json object.
my code is this :
var style = {
position:'fixed',
top:0,
right:0,
bottom:0,
left:0,
background:'red'
}
var el = document.getElementById( 'some_id' );
for( var key in style ){
el.style.key = style[key]
}
but when a run my script i get "Uncaught TypeError: Cannot read property 'style' of null"
Code example:
Object.assign(document.querySelector('.my-element').style, {
position: 'fixed',
top: 0,
right: 0,
bottom: 0,
left: 0,
background: 'red'
})
Example on JSFiddle:
https://jsfiddle.net/b6hexafL/4/
This seems to work well if you want to generate one or more iframes on loading:
var dir,name,ele,style,k,v;
dir = ...
name = ...
ele = $(document.createElement("iframe"));
$("#layout",parent.document).append(ele);
ele.attr({
src: dir +"/" +name +".html",
id: dir +name
});
style = nset[dir].monitor[name].css;
$.each(style,function(k,v){
ele.css(k,v)
});
ele.load(function(){
//next iframe or start function ... can use loaded frames
});
with relevant part of nset like this:
"lert": {
"css":{
"left": 100 ,
"top": 0 ,
"width": 320 ,
"height": 480 ,
"display": "none",
"overflow": "hidden",
"backgroundColor":"white"
}
}
You should write:
for (var key in style) {
el.style[key] = style[key]
}
Example Fiddle of what you are trying to implement:
for(var key in s) {
el.style[key] = s[key]
}

Correct architecture for prototype objects

Seeing as you can't access properties of sibling methods in a javascript object, I've been using the prototype method to extend those properties.
var ColorGen = function ColorGen() {}
ColorGen.prototype = {};
ColorGen.prototype.settings = {
gridContainer : 'gridContainer',
xSquareCount : 50,
ySquareCount : 50,
xLength : 500,
yLength : 500,
gridArr : []
};
ColorGen.prototype.totalSquares = function() {
return (this.settings.xSquareCount * this.settings.ySquareCount);
};
ColorGen.prototype.squareDim = function(length, count) {
return Math.round(length / count);
};
ColorGen.prototype.hueStep = function() {
return (360/this.totalSquares());
};
ColorGen.prototype.populateGrid = function() {
var width = this.squareDim(this.settings.xLength, this.settings.xSquareCount),
height = this.squareDim(this.settings.yLength, this.settings.ySquareCount);
for(var i=0, k = this.settings.xSquareCount * this.settings.ySquareCount; i < k; i++ ) {
var square = document.createElement('DIV');
square.setAttribute("style", "background: hsla("+(Math.round(this.hueStep() * i))+", 100%, 50%, 1.0); width: "+width+"px; height: "+height+"px; display: inline-block; position: relative;");
this.settings.gridArr.push(square);
}
};
ColorGen.prototype.setGridContainer = function() {
document.getElementById(this.settings.gridContainer).setAttribute('style', 'width: '+this.settings.xLength+'px; height: '+this.settings.yLength+'px; position: relative; overflow: hidden;');
}
ColorGen.prototype.appendGrid = function() {
var gridSquares = this.settings.gridArr;
for(square in gridSquares) {
if (document.getElementById(this.settings.gridContainer) !== null) {
document.getElementById(this.settings.gridContainer).appendChild(gridSquares[square]);
}
}
}
var colorgen = new ColorGen();
colorgen.setGridContainer();
colorgen.populateGrid();
colorgen.appendGrid();
Here's the fiddle:
http://jsfiddle.net/Ua6Mp/embedded/result/
Question: Is this an appropriate utilization of the prototype method? If not, what is the convention for extending access to a sibling method's properties?
I may not be phrasing this correctly. Please feel free to edit this question if you think it could be described more clearly
When you're using name.prototype.method = function() {} where name is an object you are dealing with JavaScript classes. As far as I know, many JavaScript frameworks use this (maybe jQuery too). I haven't heard of properties in JavaScript classes yet.

Reversal of the value of variable upon callback

How can I achieve this? Firstly the code...
function flutter() {
var random = Math.floor(Math.random()*5);
var $obj = $('.bird');
$obj.animate({ top :'-=' + random + 'px' }, 20, flutter);
}
</script>
In the code above, when the callback is executed, I want to reverse the value of random. My goal is thus to move the Class bird up and down and try to see if it create fluttering effect.
You can use some closure like this:
$obj.animate({ top :'-=' + random + 'px' }, 20, function(){
flutter(random*-1);
});
And this is the full code:
function flutter(offset) {
var random = ( isNaN(offset) ) ? Math.floor(Math.random()*5) : (offset) ;
var $obj = $('.bird');
$obj.animate({ top :'-=' + random + 'px' }, 20, function(){
flutter(random*-1);
});
}
And first call will be simple: flutter();
I just tweaked flutter above to make it more efficient and convenient.
function flutter(distance, target) {
// you can call flutter without argument. And no repetitive element finding is needed
var random = distance || Math.floor(Math.random()*5);
var $obj = target || $('.bird');
$obj.animate({ top :'-=' + random + 'px' }, 20, function(){
flutter(-random, $obj);
});
}

Use variables in other function jquery

function Main(BombPosTopr, BompPosLeftr){
if (CheckRight == false){
//$("#Main").prepend('<div class="Effect" style="absolute; top:' + BombPosTopr + 'px; left: '+ BombPosLeftr +'px;"></div>');
ArrayEffects.push(new EffectVoorBom(BombPosTopr,BombPosLeftr));
BombPosLeftr += 30;
}
};
this.explosionTime2 = setTimeout( function(){
**self2.removeEffect();**
}
}
function EffectBom(BombPosTopr, BompPosLeftr){
var self2 = this;
this.el = $('<div/>');
this.el.addClass('Effect');
this.el.css({position : 'absolute', top : BombPosTopr + 'px', left : BompPosLeftr+'px'});
$("#Main").prepend(this.el);
self2.removeEffect = function(){
**self2.el.remove();**
}
I have 2 functions and in my main I need to add Effects, so I put them in an array and use the object EffectBom.
Now the big problem is that I need to use self2.removeEffect() in my other function but it can't find it!
Thnx for reading - helping!
You need to change the scope of the variable. Add
var self2;
to the top of the file and change
var self2 = this;
to be
self2 = this;

How to add a new item to the end of the list using jQuery?

I have this function for adding a new item to the beginning of the list and removing the last one:
function addItem(id, text){
var el = $('#' + id);
var w = el.width();
el.css({
width: w,
overflow: 'hidden'
});
var ulPaddingLeft = parseInt(el.css('padding-left'));
var ulPaddingRight = parseInt(el.css('padding-right'));
el.prepend('<li>' + text + '</li>');
var first = $('li:first', el);
var last = $('li:last', el);
var fow = first.outerWidth();
var widthDiff = fow - last.outerWidth();
var oldMarginLeft = first.css('margin-Left');
first.css({
marginLeft: 0 - fow,
position: 'relative',
left: 0 - ulPaddingLeft
});
last.css('position', 'relative');
el.animate({ width: w + widthDiff }, 1500);
first.animate({ left: 0 }, 250, function() {
first.animate({ marginLeft: oldMarginLeft }, 1000, function() {
last.animate({ left: ulPaddingRight }, 250, function() {
last.remove();
el.css({
width: 'auto',
overflow: 'visible'
});
});
});
});
}
How can I make it work the other way around ? I want to add the item to the end and remove the first and also make it slide the other way around, like right to left.
Take a look at jQuery.append (and jQuery.prepend for beginning of list)
Your code seems really complicated. Simplifying it a little bit might give you something like this:
$("#whateverList").addItem("awesome")
jQuery.fn.addItem = function(text) {
var $li = $("<li>").text(text)
$(this).find("li:first").remove()
$(this).append($li)
}
jQuery plugin syntax is super easy to understand
append() to go to the bottom
var declarations at the top
Good luck!

Categories

Resources