javascript css call by variable not working in Android browser - javascript

I am looping through a set of images, and then setting their height to match a variable. The following code is working just fine with Firefox, however is unresponsive in Android's browser. Thoughts?
var x = 100;
count_li = 5;
for (var i = count_li - 1; i >= 0; i -= 1) {
var carousel_img = '#carousel_img_' + [i];
$(carousel_img).css('height', x);
}
Where I have a set of 5 images that might look like this:
<img id="carousel_img_0" src="img_0.jpg"/>
<img id="carousel_img_1" src="img_1.jpg"/>
etc...
Here is a similar post for reference, but I'm not finding what I need in it.
A secondary, directly connected issue is that this code is having the exact issue:
var img_w = $(carousel_img).width();
Presumably it too needs a 'px' reference, but I'm unaware of the syntax.
Solutions ----------------------------------------------------------
As stated by Matt, this
$(carousel_img).css('height', x);
needed to have a 'px' added to the end, as seen below:
$(carousel_img).css('height', x + 'px');

Related

Trying to setAttribute to a button Element in a Class dynamically but returns "is not defined"

I have this problem. I'm creating in Javascript a game similar to minefield - i decided to use a Class to generate the game levels. The Class is also in charge to generate the DOM code, including the buttons and the layout, according with the level size defined when creating the level.
Now the issue i have is that when i generate the code for each button:
box.setAttribute('onclick', this.levelName + '.checkResult(this.id)');
In the generate HTML it seems to be correct:
<button id="00" class="box" onclick="LevelOne.checkResult(this.id)">test</button>
But when i press the relative button i get this message:
Uncaught ReferenceError: LevelOne is not defined
at HTMLButtonElement.onclick (findTheSpot.html:16)
And if i do this, inserting the variable name directly in the second parameter:
box.setAttribute('onclick', 'levelOne.checkResult(this.id)');
It works perfectly.
I will paste the entire code below just to help you to visualize the entire flow - i'm totally new to javascript and i'm trying to learn as much as i can, creating different coding exercises by my own, apologies in advance for any coding horrors or rookie mistakes :D
/// creating a class to generate an array map of 0s and a single random 1
class Level {
constructor(wL, hL) {
this.widhtLevel = wL;
this.lenghtLevel = hL;
this.levelName;
this.level = [];
}
populateLevel() {
var idNumber = 0;
//Creating the main div container
var div = document.createElement('div');
div.style.width = this.widhtLevel + (this.widhtLevel * 50) + 'px';
div.style.height = this.lenghtLevel + (this.lenghtLevel * 50) + 'px';
div.setAttribute('id', 'mainContainer');
div.setAttribute('class', 'boxContainer');
document.body.appendChild(div);
for(var i = 0; i < this.lenghtLevel; i++) {
var arrayPopulation = []
for(var j = 0; j < this.widhtLevel; j++) {
arrayPopulation.push(0)
//Creating the boxes
var box = document.createElement('button');
box.textContent = "test";
box.setAttribute('id', idNumber + '' + (arrayPopulation.length - 1));
box.setAttribute('class', 'box');
box.setAttribute('onclick', this.levelName + '.checkResult(this.id)');
div.appendChild(box);
}
this.level.push(arrayPopulation);
idNumber++;
}
}
randomizeKey() {
var randomX = Math.floor(Math.random() * (this.widhtLevel - 0));
var randomY = Math.floor(Math.random() * (this.lenghtLevel - 0));
this.level[randomY][randomX] = 1;
//console.log(this.level[randomY][randomX]);
}
createLevel(name) {
this.levelName = name;
this.populateLevel()
this.randomizeKey()
for (var i = 0; i < this.level.length; i++) {
console.log(this.level[i])
}
}
var levelOne = new Level(5,5);
levelOne.createLevel("LevelOne");
The problem comes down to a common programming nightmare - capitalization. It can be incredibly frustrating trying to debug a problem caused by inconsistent capitalization because your brain often skips that detail when comparing variable names. In your case your generated code capitalizes "LevelOne" but your hardcoded value is "levelOne". You may have to read the previous sentence twice to notice the difference even though it was explicitly called out.
So the short-term answer to your problem is that you need to make sure that the variable name and the "levelName" property have the same capitalization. Without taking the time to review the rest of your code that should at least fix the immediate issue.
While you are reviewing this, it would not hurt to think about your variable capitalization conventions. You do not have to rename all of your variables immediately but you may find that defining personal standards will make future code far more maintainable. If you work with other developers then this is an exercise that you should undertake together or you may find yourselves unintentionally working against each other. If you already have naming conventions then feel free to ignore this advice - maybe it will help someone else viewing this answer later.

How to assign values to a jquery object using for loop

I have tried several ways to create a parallax effect on my images where each image has it's own random speed. I think the best way for me to achieve it is by assigning a speed value to each image. However I am not sure how to do this.
var img_list = [];
$.each($('.gallery_image'), function(e) {
img_list.append($(this));
});
for(x in img_list) {
ran = Math.round(Math.random() * (11 - 1) + 1);
speed = ran.toString() + "px";
x.speed = speed;
}
This is what I came up with. I know that x.speed is not an actual thing, but I am using that to illustrate what I am trying to accomplish.
This is a website that has exactly what I am looking for on the main page, but I want the movement to be on scroll. EXAMPLE
for(var x in img_list) {
var ran = Math.round(Math.random() * (11 - 1) + 1);
img_list[x].speed = ran.toString() + "px";
}
Use push
var img_list = [];
$.each($('.gallery_image'), function(e) {
img_list.push($(this));
});
but in this case you don't need a loop because $('.gallery_image') is a collection of objects
In the second loop you can use a each loop and save the speed as a data attribute:
$('.gallery_image').each(function(i,x){
ran = Math.round(Math.random() * (11 - 1) + 1);
speed = ran.toString() + "px";
$(x).data('speed',speed);
});
I dont know if this is relative or not ,but I made a demo .
Hope this helps.
To move image set left css property of dom.
DEMO
https://jsfiddle.net/vikrant47/yem6f0Ls/4/

SharePoint 2013 App Part - Not using iFrame or flowing elements outside of iFrame

I am currently developing an App Part that is attached to an Associate Directory application.
As one of the methods of finding someone, I have implemented a custom implementation of the jQuery UI Autocomplete widget (http://jqueryui.com/autocomplete/).
My problem is that according to the design for our homepage, where this app part is going to be placed, this isn't very tall.
So my issue is that when the dropdown comes down, for the autocomplete, a portion of it gets cut off. (See image below)
I know I do have some options with the styling to make it smaller and show more, but either way I would like to see if there are any more options for me.
My first thought was that I could make this into a Web Part, but then I would have to duplicate a lot of code from the application.
Please let me know if there are any ideas!
Thank you, Eric
Set the height in the app part elements.xml to that of the dropdown. When its focused you run a script that resizes your app part window to the height of your content.
My app part does an async call that renders an array as rows in the app part. On the last row i run below code.
var senderId;
var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var param = params[i].split("=");
if (param[0].toLowerCase() == "senderid")
senderId = decodeURIComponent(param[1]);
}
var step = 77,
newHeight = 0,
arrayLength = scope.items.length,
resizeMessage = '<message senderId={Sender_ID}>resize({Width}, {Height})</message>';
for (var x = 0; x < arrayLength; x = x + 1) {
newHeight = newHeight + step;
}
if (senderId) {
resizeMessage = resizeMessage.replace("{Sender_ID}", senderId);
resizeMessage = resizeMessage.replace("{Height}", newHeight);
resizeMessage = resizeMessage.replace("{Width}", "100%");
window.parent.postMessage(resizeMessage, "*");
}
A couple of other examples:
Example 1
Example 2

Javascript style.left is empty string

next.onclick = function() {
move('left', li_items[0]);
};
var move = function(direction, el) {
pos = el.style[direction].split('px')[0];
pos = parseInt(pos, 10) + 10;
el.style[direction] = pos + 'px';
};
I'm using the simple code above to try and move an element. Now when I breakpoint on this, the value of el.style[direction] is: " ". So then when i try to do anything with it, it breaks. Why would this be? Isn't style.left supposed to return an integer?
Why would this be?
Presumably because it hasn't been set to anything.
Isn't style.left supposed to return an integer?
No. It is supposed to return a string containing the value of the CSS left property as set directly on the element (either by setting the JS property itself or by using a style attribute). It does not get a value from the cascade and it should only be an integer if the value is 0 (since all other lengths require units).
See How to get computed style of a HTMLElement if you want to get the computed value for the property rather than what I described in the previous paragraph.
style provides the original style as calculated from the CSS, not the updated and possibly dynamic style. You probably want currentStyle instead.
next.onclick = function() {
move('left', li_items[0]);
};
var move = function(direction, el) {
var lft = document.defaultView.getComputedStyle(el)[direction];
pos = parseFloat(lft);
pos = parseInt(pos, 10) + 10;
el.style[direction] = pos + 'px';
};
Note: like Elliot said you'll have to get the currentStyle/computedStyle. Here's a way to make it cross-browser, however when applying styles via JS, this is one good case where some sort of framework (eg Prototype [Scriptaculous], jQuery) would be useful.
Just a comment.
In your code:
> pos = el.style[direction].split('px')[0];
> pos = parseInt(pos, 10) + 10;
The split in the first line is superfluous, in the second line parseInt will convert (say) 10px to the number 10 just as effectively (and more efficiently) than what you have.
pos = parseInt(el.style[direction], 10);

how to get the actual box bigger than the others?

i'm new to javascript and i'm having a problem. I want the actual (function updateBoxes) box [boxIx] to be bigger than the other ones but i can't seem to find a code that works. i've tried box[boxIx].size ="100px"; box[boxIx].style.size ="100px"; without result. This is my code;
function init() {
box = document.getElementById("boxes").getElementsByTagName("div");
for (var i=0; i<box.length; i++) {
box[i].style.left = 70*i+"px";
} // End for
boxIx = box.length - 8;
updateBoxes();
} // End init
function browseLeft() {
if (boxIx > 0) boxIx = boxIx - 1;
updateBoxes();
}
// End browseLeft
function browseRight() {
if (boxIx < box.length-1) boxIx = boxIx + 1;
updateBoxes();}
// End browseRight
**function updateBoxes() {
box[boxIx].style.backgroundColor ="#CCC";
box[boxIx].style.top = "20px";
box[boxIx].style.zIndex = 9;**
var z = 8;
for (var i=boxIx-1; i>=0; i--) {
box[i].style.backgroundColor ="#666";
box[i].style.top = "0px";
box[i].style.zIndex = z;
z = z - 1;
} // End for
z = 8;
for (var i=boxIx+1; i<box.length; i++) {
box[i].style.backgroundColor = "#666";
box[i].style.top = "0px";
box[i].style.zIndex = z;
z = z - 1;
} // End for
} // End browseLeft
As thirtydot pointed out, you have two instances of "**" in your sample code that I've removed in the assumption that this is a markdown glitch when editing.
Your example shows only the JavaScript code. The HTML markup and CSS styling you're using would be most helpful. I've created a fiddle for discussion and to resolve this for you here: http://jsfiddle.net/bhofmann/zkZMD/
A few things I noticed that might be helpful:
You're using a magic number 8 in a few places. Can we assume this is the number of boxes? I would store that in a variable for use in the functions.
You used a lot of direct styling. Your code might be cleaner if you used CSS classes to alter the appearance of the boxes.
Unless you're altering the default styling of DIV, you won't see much change by simply setting the left offset.
PS. I took the liberty of invoking the init function on page load because I saw nothing else to invoke it. I don't know what would invoke browseLeft and browseRight but I'll leave that to you.

Categories

Resources