Javascript variable working without var? - javascript

I am trying to write an image slider in Javascript, I was looking at examples online and found this particular one:
function slider(){
var current = 0;
slides = document.getElementsByClassName("images");
setInterval(function() {
for (var i = 0; i < slides.length; i++) {
slides[i].style.opacity = 0;
}
current = (current != slides.length - 1) ? current + 1 : 0;
slides[current].style.opacity = 1;
}, 3000);
}
window.onload=slider;
I have tested this and it works with no errors.
I am wondering why the variable 'slides' is not declared as 'var slides', when I add 'var' the script stops working.
Don't all variables in Javascript start with 'var'? why does this work without the 'var'?

Correctly declaring slides as var slides does not break this function.
Run the example below.
function slider() {
var current = 0;
var slides = document.getElementsByClassName("images");
setInterval(function() {
for (var i = 0; i < slides.length; i++) {
slides[i].style.opacity = 0;
}
current = (current != slides.length - 1) ? current + 1 : 0;
slides[current].style.opacity = 1;
}, 3000);
}
window.onload=slider;
<div class="images">image1</div>
<div class="images">image2</div>
<div class="images">image3</div>

Related

why am i getting a timeout on my loop (js)

I have a loop that puts img elements next to each other inside a div, however, my loop doesnt work. i get a timeout, but I don't know why.. Is there something obvious I'm missing?
for(var i = 0; i < 3; i++){
var hatch = document.createElement('img');
hatch.src = "img/Sand.png";
hatch.style.width ="1cm";
hatch.style.position = "absolute";
for(var x=0; Math.ceil((cm2px(2.5)-1)/cm2px(1)) < x; x++) {
if (x != 0) {
hatch.style.left = `"${x*cm2px(1)}cm"`;
}
}
Lith.appendChild(hatch);
}
the condition of the inner loop is > instead of <

this function cause browser crash

I have written a function that i want to detect the language of the text based on utf-8 encoding.Actualy this function determines the input argumant is english or not.The function work correctly in javascript console but when I use it in a loop ,the browser crashes.
//titles.lenght=>90
function is_eng(title) {
var A = 65;
var z = 122;
title = title.toString();
var eng_chars = 0;
var non_eng_chars = 0;
for (i = 0; i < title.length; i++) {
var c = title.charCodeAt(i);
if (c > A && c < z) {
eng_chars += 1;
} else {
non_eng_chars += 1;
}
}
if (eng_chars > non_eng_chars) {
return 1;
}
return 0;
}
You should add the keyword var before i=0, otherwise i is a global variable. If you use i for the external loop, you have an endless loop.

I am trying to set bottom of element but its value is coming up NaN

function CheckavailOnload()
{
var elems = document.getElementsByClassName('box-collateral box-related');
var av = document.getElementsByClassName('availability in-stock');
var x;
for (var i = 0; i < elems.length; i++)
{
if (getComputedStyle(elems[i]).visibility == 'visible')
{
for (var j = 0; j < av.length; j++)
{
av[j].style.visibility = 'visible';
if(elems[i].offsetTop < 0)
{
var x = (elems[i].offsetHeight + (elems[i]).offsetTop).toString() + "px";
alert(x);
}
for(m = 0;m < av.length; m++)
{
av[m].style.Bottom = (-x);
return;
}
}
}
}
for (var k = 0; k < av.length; k++)
{
av[k].style.visibility = 'hidden';
}
var divs = document.getElementsByClassName('add-to-cart');
for(var l = 0; l < divs.length; l++)
{
divs[l].style.marginTop = (-500).toString() + "px";
divs[l].style.marginLeft = (-20).toString() + "px";
}
}
window.onload = CheckavailOnload;
here i am trying to move a paragraph tag have baground image depending upon the div offsetTop and Offset height div also have bacground image i am moving para tag just below the div but addition of offsetHeight and offsetTop is coming NAN please anyone can help me
You've declared var x; at the beginning of your script. Then later you're checking:
if(elems[i].offsetTop < 0) {
var x = (elems[i]...); // var is not recommended to be here, x has been already declared once
}
If elems[i].offsetTop happens to be >= 0, x will be undefined in this line:
av[m].style.Bottom = (-x); // Notice a typo here: should be av[m].style.bottom
This last expression gives you NaN. To avoid this, you need to either assign a default value to x in the beginning of the script, or add an else statement after the if wherein some numeric value is assigned to x.
Also return in the for...m-loop seems to break your code, the loop will never finish the job and the rest of the code will be never executed.
Using (-500).toString() + "px"; feels complex, why not just use "-500px";?

increasing the row number using JavaScript?

I'm trying to increase the row each time around the loop, but it's not increasing is there something wrong with my JavaScript code?
var image= [];
for (var i = 0; i < test.length; i++) {
var avatar = test[i].image; // The profile image
var row =5;
if(i % 2 === 0){
image[i]= Titanium.UI.createImageView({
top:row,
image:avatar
});
win.add(image[i]);
//trying to increase the image
row =row+200;
} else if(i % 2 === 1) {
image[i]= Titanium.UI.createImageView({
top:row,
image:avatar
});
win.add(image[i]);
}
}
Can't say I'm certain of what you're attempting to achieve, but at the beginning of your for iteration you're resting row to 5. You should move your var row=5; declaration to the top with var image[];
You might also consider the short form row+=200;
try to move this line upper outside of the loop :
var image= [];
var row =5;
for (var i = 0; i < test.length; i++) {
...
}
You are initializing row in each start of loop. Try taking your var row = 5 outside of the loop:
var image= [];
var row =5;
for (var i = 0; i < test.length; i++) {
var avatar = test[i].image; // The profile image
...
}

Javascript/Dom loading images in to grid

I'm pretty new to programming and javascript/dom. Ultimately, I'm trying to make a sliding puzzle game but to start off with, I'm just trying to get the images loading up in a random order. It's going to be a 4x4 grid of images. The images are named Tree00, 01, 02, 03, 10, etc up to 33. Here's my code so far:
<html>
<head>
<title>Shuffle</title>
</head>
<body>
<script language="JavaScript">
<!--
Pics = new Array();
var Top = 16;
for(i = 0; i < Top; i++) {
document.write("<img><img><img><img><br>");
}
function RandomInt(Min, Max) {
RI = Math.floor(Math.random() * (Max - Min + 1)) + Min;
return(RI);
}
function Shuffle() {
N = RandomInt(0, 1);
this.Image.src=Pics[N];
this.Image.style.left = 220;
}
function ViewerObj(Image, Pics, i) {
this.Image = Image;
this.Image.style.left = 800;
this.Pics = Pics;
this.Shuffle = Shuffle;
this.Image.id = "ID" + i;
}
function Randomise() {
var i;
for(i = 0; i < Top; i++) {
Viewers[i].Shuffle();
Viewers[i].Image.style.left = 200;
}
}
Viewers = new Array();
var i;
for(i = 0; i < 3; i++) {
Pics[i] = "images/Tree" + (i) + (i + 1) + ".jpg";
}
for(i = 0; i < Top; i++) {
document.images[i].src = "images/Blank.jpg";
document.images[i].style.left = 300;
Viewers[i] = new ViewerObj(document.images[i], Pics, i);
}
//-->
</script>
<h1>Shuffle</h1>
<form>
<input type="button" value="Shuffle" onClick="Randomise();"/>
</form>
</body>
</html>
I just can't quite fathom what I need to be changing and how I'd go about it. Any help + explanation would be much appreciated. What I am trying to achieve is it loading every image but just in a random order, but with no duplicates.
Here are a few problems in your script :
first replace
for(i = 0; i < Top; i++) {
document.write("<img><img><img><img><br>");
}
by
for(i = 0; i < Top; i++) {
document.write("<img>");
if ((i+1)%4 == 0) {
document.write("<br>");
}
}
you will get only 16 IMG elements instead of 4*16 in your code
then you will need 16 different names for your images : replace
for(i = 0; i < 3; i++) {
Pics[i] = "images/Tree" + (i) + (i + 1) + ".jpg";
}
by
for(var i = 0; i < 4; i++) {
for(var j = 0; j < 4; j++) {
Pics[j+4*i] = "images/Tree" + (i) + (j) + ".jpg";
}
}
Then you biggest problem is the shuffling. You cannot shuffle the "Viewers" one-by-one because you want to avoid duplicates. Each viewer must randomly select a unique image.
For this you can use the technique in mdarwi's answer : shuffle the Pics table for instance.
check your modified code on jsbin here
If your problem is simply that you'd like the images to be properly shuffled, you can use the following code (taken directly from the Javascript sample code for the Fisher-Yates shuffle on Wikipedia:
var n = a.length;
for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
The easiest thing to do would be to rename your images Tree1 to TreeN, and then place N integers in an array and shuffle them using the above algorithm.
(This is a code-comment, not an answer)
Pics = new Array();
The Pics variable should be declared before using. Also, use the shorthand notation []
var Pics = [];
var Top = 16;
for (i = 0; i < Top; i++) {
document.write("<img><img><img><img><br>");
}
The i variable is declared only later in the code. It should be declared at the top of the program.
function RandomInt(Min, Max) {
RI = Math.floor(Math.random() * (Max - Min + 1)) + Min;
return (RI);
}
This is particularly dangerous: the RI variable is not declared inside the function, so it becomes an implicit global property. That should be avoided. Also, the parens in the return statement are superfluous.
function RandomInt(Min, Max) {
return Math.floor(Math.random() * (Max - Min + 1)) + Min;
}
function Shuffle() {
N = RandomInt(0, 1);
this.Image.src = Pics[N];
this.Image.style.left = 220;
}
Again, the N variable should be declared. Also, why is this "method" declared outside of the ViewerObj constructor? Either, put it inside, or - even better - add it to the constructors prototype object. That way, there will only be one Shuffle function object instead of many.
function ViewerObj(Image, Pics, i) {
this.Image = Image;
this.Image.style.left = 800;
this.Pics = Pics;
this.Shuffle = Shuffle;
this.Image.id = "ID" + i;
}
function Randomise() {
var i;
for (i = 0; i < Top; i++) {
Viewers[i].Shuffle();
Viewers[i].Image.style.left = 200;
}
}
Viewers = new Array();
var i;
As mentioned above, the i variable should be declared on top. Also, the Viewers variable should be declared.
var Viewers = [];
for (i = 0; i < 3; i++) {
Pics[i] = "images/Tree" + (i) + (i + 1) + ".jpg";
}
for (i = 0; i < Top; i++) {
document.images[i].src = "images/Blank.jpg";
document.images[i].style.left = 300;
Viewers[i] = new ViewerObj(document.images[i], Pics, i);
}

Categories

Resources